Monday, 4 May 2015

Looping through a map in Java

Before knowing how to loop/iterate a Map, HashMap/TreeMap in Java, we need to know about two methods declared by Map interface that play a role in, how to iterate through 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.

Now, when we know about these two methods let's see how they can be used to loop through a map. We can use either an iterator or a For-Each loop to iterate through a map. Here in the example code HashMap is used.

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");
  // First way with 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 with 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());
  }

 }
}

It can be seen that the first iteration is done using the keySet() method which gives a set of keys in the map. Using those keys respective values are retrieved.

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() method.

Third way of iteration is again using the entrySet() method, only difference is instead of using the For-Each loop, iterator is used here.

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 with 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

Using Java 8 lambda expression

Starting Java 8 a ForEach loop is provided to be used along with Lambda expression too, which reduces the looping to a single statement. Another feature of Java 8, method reference makes it even shorter.

Example code

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 For each functionality");
  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 Lambda expression method reference For each functionality");
  cityMap.entrySet().forEach(System.out::println);
 }
}

Output

Looping with Lambda expression For each functionality
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 Lambda expression method reference For each functionality
1=New York City
2=New Delhi
3=Newark
4=Newport

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 is using keySet() which returns a set containing keys of the map.
  • Map can be iterated either using iterator or for-each loop or even simple for loop.
  • With Java 8, forEach loop using lambda expression provides a new way to loop a collection.

That's all for this topic Looping through a map in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How HashMap internally works in Java
  2. How to loop/iterate an arraylist in Java
  3. LinkedHashMap in Java
  4. Treemap in Java
  5. How to Sort elements in different order in TreeSet using Comparator
  6. Java Collections interview questions

You may also like -

No comments:

Post a Comment