HashMap is one of the most used data collection. There are several ways how to loop over it and get what you need. We will show five different ways how to loop over HashMap. So what is the best way to iterate over the items in a HashMap?
First of all, if you are interested only in the HashMap keys, you can iterate through for
loop using keySet()
method of the HashMap class:
Map<Long, Object> map = ...; for (Long key : map.keySet()) { // ... }
If you are interested only in HashMap values, you iterate through for
loop using values()
method of the HashMap class:
Map<Long, Object> map = ...; for (Object value : map.values()) { // ... }
There are 2 different ways how to loop over HashMap if you want to use the key and the value at the same time. Both options use entrySet()
. The first possibility is by using for loop:
Map<Long, Object> map = ...; for (Map.Entry<Long, Object> entry : map.entrySet()) { Long key = entry.getKey(); Object value = entry.getValue(); // ... }
The second option is by using Iterator
:
Map<Long, Object> map = ...; Iterator it = map.entrySet().iterator(); while (it.hasNext()) { Map.Entry entry = (Map.Entry)it.next(); Long key = entry.getKey(); Object value = entry.getValue(); //... }
And the last option is over lambda expression
and suitable more for one line solutions. :
Map<Long,Object> map = new HashMap<Long, Object>(); myMap.forEach((k,v) -> System.out.println("Key: " + K + " Value:" + V)); myMap.forEach((k,v) -> { // System.out.println("Key: " + k + " Value:" + v)); Long key = k; Object value = v; }