To loop or iterate any Map implementation like HashMap or Treemap in Java, you need to know about three methods declared by Map interface that play a role in iterating a Map.
- Set<Map.Entry<K, V>> entrySet()- This method returns a set that contains the entries in the map. The entries in the set are actually object of type Map.Entry.
- Set<K> keySet()- This method returns a set that contains the keys of the map.
- Collection<V> values()- This method returns a Collection view of the values contained in this map.
Now, when you know about these three methods let's see how these methods can be used to loop through a HashMap in Java.
- You can use either an iterator or a For-Each loop to iterate through a Map. See example.
- Java 8 onwards you can also use forEach statement. See example.
HashMap iteration using for-each and iterator Java example
In the example code HashMap is used to demonstrate traversal of a Map.
public class HashMapLooping { /** * @param args */ public static void main(String[] args) { // Setting up a HashMap Map<String, String> cityMap = new HashMap<String, String>(); cityMap.put("1","New York City" ); cityMap.put("2", "New Delhi"); cityMap.put("3", "Newark"); cityMap.put("4", "Newport"); System.out.println("Looping with keySet"); // Loop through HashMap using Key Set Set<String> citySet = cityMap.keySet(); for(String key : citySet){ System.out.println("Key is " + key + " Value is " + cityMap.get(key)); } System.out.println("Looping HashMap using entrySet"); // Second way with entrySet for(Map.Entry<String, String> entry: cityMap.entrySet()){ System.out.println("Key is " + entry.getKey() + " Value is " + entry.getValue()); } System.out.println("Looping with entrySet using Iterator"); //Third way with iterator Iterator<Entry<String, String>> itr = cityMap.entrySet().iterator(); while(itr.hasNext()){ Map.Entry<String, String> entry = itr.next(); System.out.println("Key is " + entry.getKey() + " Value is " + entry.getValue()); } System.out.println("Looping HashMap using values method"); for(String value : cityMap.values()){ System.out.println("Value is " + value); } } }
It can be seen that the first iteration of the HashMap is done using the keySet()
method which gives a set of keys
in the map. Using those keys respective values are retrieved. Since another call is required to get the mapped values this way
of looping a HashMap is less efficient in case you need both keys and values.
Second iteration of the map is done using the entrySet()
method which returns a set containing the
Map.Entry objects. From Map.Entry object key and value can be retrieved using getKey()
and getValue()
methods.
Third way of iteration is again using the entrySet()
method, only difference is instead of using the
For-Each loop, iterator is used here.
Fourth way of iterating a HashMap uses the values()
method and gives all the values stored in the HashMap.
Output of the program
Looping with keySet Key is 1 Value is New York City Key is 2 Value is New Delhi Key is 3 Value is Newark Key is 4 Value is Newport Looping HashMap using entrySet Key is 1 Value is New York City Key is 2 Value is New Delhi Key is 3 Value is Newark Key is 4 Value is Newport Looping with entrySet using Iterator Key is 1 Value is New York City Key is 2 Value is New Delhi Key is 3 Value is Newark Key is 4 Value is Newport Looping using values method Value is New York City Value is New Delhi Value is Newark Value is Newport Value is Kolkata
Iterating HashMap using forEach statement
Java 8 onward forEach statement is provided to be used along with Lambda expression in Java, which reduces the looping through a Map to a single statement. Another feature of Java 8, method reference makes it even shorter. With forEach statement you can even iterate a HashMap directly without getting a collection view of the Map.
- Refer lambda expression example tutorial Lambda expression examples in Java 8 to know more about lambda expressions.
public class HashMapLooping { /** * @param args */ public static void main(String[] args) { // Setting up a HashMap Map<String, String> cityMap = new HashMap<String, String>(); cityMap.put("1","New York City" ); cityMap.put("2", "New Delhi"); cityMap.put("3", "Newark"); cityMap.put("4", "Newport"); System.out.println("Looping with Lambda expression forEach stmt"); Set<Map.Entry<String, String>> valueSet = cityMap.entrySet(); valueSet.forEach((a)->System.out.println("Key is " + a.getKey() + " Value is " + a.getValue())); System.out.println("Looping with method reference forEach"); cityMap.entrySet().forEach(System.out::println); // Looping HashMap directly with forEach System.out.println("Looping HashMap with forEach statement"); cityMap.forEach((K,V)->System.out.println("Key is " + K + " Value is " + V)); } }
Output
Looping with Lambda expression forEach stmt Key is 1 Value is New York City Key is 2 Value is New Delhi Key is 3 Value is Newark Key is 4 Value is Newport Looping with method reference forEach 1=New York City 2=New Delhi 3=Newark 4=Newport Looping HashMap with forEach statement Key is 1 Value is New York City Key is 2 Value is New Delhi Key is 3 Value is Newark Key is 4 Value is Newport Key is 5 Value is Kolkata
Points to note-
- A map can be iterated using entrySet() which returns a set containing objects of type Map.Entry.
- Another way to iterate a map in Java is using keySet() method which returns a set containing keys of the map or values() method that returns a Collection view of the Map.
- Map can be iterated either using iterator or for-each loop.
- With Java 8 forEach statement provides a new way to loop a HashMap in Java.
That's all for this topic How to Loop Through a Map in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!
Related Topics
You may also like-
No comments:
Post a Comment