December 30, 2023

How to Iterate a Java HashMap

In this post we’ll see different ways to iterate a Map or HashMap in Java. One thing you should know is you can’t directly loop a Map in Java (except when you use forEach statement). There are methods that return a "collection view" of the Map using that view you can iterate a HashMap in Java.

The methods that can be used for getting a "collection view" of the Map are as follows-

  • Set<Map.Entry<K,V>> entrySet()- Returns a Set view of the mappings contained in this map.
  • Set<K> keySet()- Returns a Set view of the keys contained in this map.
  • Collection<V> values()- Returns a Collection view of the values contained in this map.

Options for iterating a Java HashMap

As you can see from the above methods you either get a Set with Map.entry elements, a Set of keys of the maps or a Collection view of the Map values.

Using that view you can iterate a Map in Java using one of the following options-

  1. You can use For-Each loop (enhanced for loop), available from Java 5.
  2. You can iterate using Iterator. Using iterator() method you can get an iterator and then using the hashNext() and next() method of the iterator you can iterate a HashMap.
  3. You can also use forEach statement available from Java 8 to loop through Map.

Iterate a HashMap in Java - Examples

Here are some examples using all of the above mentioned methods for iterating a HashMap.

1. Using entrySet() method

Using entrySet() method you get the set view of the mappings stored in the HashMap in the form of Map.entry elements. Using that set view you can iterate a HashMap and get both key and value.

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class HashMapIteration {
  public static void main(String[] args) {
    // Creating HashMap
    Map<String, String> carMap = new HashMap<String, String>();
    // Storing elements
    carMap.put("1", "Audi");
    carMap.put("2", "BMW");
    carMap.put("3", "Jaguar");
    carMap.put("4", "Mini Cooper");
    System.out.println("***Looping using entrySet***");
    Set<Map.Entry<String, String>> carSet =  carMap.entrySet();
        
    System.out.println("***Using for-each loop***");
    for(Map.Entry<String, String> entry : carSet){
      System.out.println("Key is " + entry.getKey() + " Value is " + entry.getValue());
    }
        
    System.out.println("***Using iterator***");
    Iterator<Map.Entry<String, String>> itr = carSet.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("***Using forEach statement***");
    carSet.forEach((c)->System.out.println("Key is " + c.getKey() + " Value is " + c.getValue()));
  }
}
Output
***Looping using entrySet***
***Using for-each loop***
Key is 1 Value is Audi
Key is 2 Value is BMW
Key is 3 Value is Jaguar
Key is 4 Value is Mini Cooper
***Using iterator***
Key is 1 Value is Audi
Key is 2 Value is BMW
Key is 3 Value is Jaguar
Key is 4 Value is Mini Cooper
***Using forEach statement***
Key is 1 Value is Audi
Key is 2 Value is BMW
Key is 3 Value is Jaguar
Key is 4 Value is Mini Cooper
2. Using keySet() method

Using keySet() method you get the set view of the HashMap keys. Once you have the keys you can also get the values mapped to those keys using the get() method but that makes the looping of the Map slow in comparison to other ways.

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class HashMapIteration {
  public static void main(String[] args) {
    // Creating HashMap
    Map<String, String> carMap = new HashMap<String, String>();
    // Storing elements
    carMap.put("1", "Audi");
    carMap.put("2", "BMW");
    carMap.put("3", "Jaguar");
    carMap.put("4", "Mini Cooper");
    System.out.println("***Looping using keySet***");
    Set<String> carSet =  carMap.keySet();
    System.out.println("***Using for-each loop***");
    for(String key : carSet){
      System.out.println("Key is " + key + " Value is " + carMap.get(key));
    }
    System.out.println("***Using iterator***");
    Iterator<String> itr = carSet.iterator();
    while (itr.hasNext()) {
      String key = itr.next();
      System.out.println("Key is " + key + " Value is " + carMap.get(key));    
    }
    System.out.println("***Using forEach statement***");
    carSet.forEach((c)->System.out.println("Key is " + c + " Value is " + carMap.get(c)));
  }
}
Output
***Looping using keySet***
***Using for-each loop***
Key is 1 Value is Audi
Key is 2 Value is BMW
Key is 3 Value is Jaguar
Key is 4 Value is Mini Cooper
***Using iterator***
Key is 1 Value is Audi
Key is 2 Value is BMW
Key is 3 Value is Jaguar
Key is 4 Value is Mini Cooper
***Using forEach statement***
Key is 1 Value is Audi
Key is 2 Value is BMW
Key is 3 Value is Jaguar
Key is 4 Value is Mini Cooper
3. Using values() method

If you just want to iterate over the values of the HashMap you can use the values() method.

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class HashMapIteration {
  public static void main(String[] args) {
    // Creating HashMap
    Map<String, String> carMap = new HashMap<String, String>();
    // Storing elements
    carMap.put("1", "Audi");
    carMap.put("2", "BMW");
    carMap.put("3", "Jaguar");
    carMap.put("4", "Mini Cooper");
        
    System.out.println("***Looping using values***");
    Collection<String> cars = carMap.values();
    System.out.println("***Using for-each loop***");
    for(String car : cars){
      System.out.println("Value is " + car);
    }
    System.out.println("***Using iterator***");
    Iterator<String> itr = cars.iterator();
    while (itr.hasNext()) {
      System.out.println("Value is " + itr.next());
    }
    System.out.println("***Using forEach statement***");
    cars.forEach((c)->System.out.println("Value is " + c));
    // forEach with method reference
    cars.forEach(System.out::println);
  }
}
Output
***Looping using values***
***Using for-each loop***
Value is Audi
Value is BMW
Value is Jaguar
Value is Mini Cooper
***Using iterator***
Value is Audi
Value is BMW
Value is Jaguar
Value is Mini Cooper
***Using forEach statement***
Value is Audi
Value is BMW
Value is Jaguar
Value is Mini Cooper
Audi
BMW
Jaguar
Mini Cooper
4. Iterating a Map directly using forEach

As the saying goes “save the best for the last” here is a way to iterate a HashMap in Java directly using forEach statement (Java 8 onward).

public class HashMapIteration {
  public static void main(String[] args) {
    // Creating HashMap
    Map<String, String> carMap = new HashMap<String, String>();
    // Storing elements
    carMap.put("1", "Audi");
    carMap.put("2", "BMW");
    carMap.put("3", "Jaguar");
    carMap.put("4", "Mini Cooper");
    
    carMap.forEach((K, V) -> System.out.println("Key is " + K + " value is " + V));
  }
}
Output
Key is 1 value is Audi
Key is 2 value is BMW
Key is 3 value is Jaguar
Key is 4 value is Mini Cooper

That's all for the topic How to Iterate a Java HashMap. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment