x Java Java 8 JUnit JSON
  • XML
  • JDBC Spring Boot Microservices React Contact Us

    Iterate through HashMap Java

    There are various ways of iterating over a Map type in Java. We will use HashMap to show various ways of iterating through a Map and same can be used for other Map implementations.

    1) Using enhanced for loop (Java 5) on Map entrySet

    You can iterate a HashMap using for loop on a Set<Map.Entry<String, String>>. You can get Set<Map.Entry<String, String>> by calling HashMap entrySet() method. The Set is backed by original HashMap so any changes in the HashMap will be reflected in the Set and vice-versa.

    Also we will use enhanced for loop so that you don't need to get the iterator. You need to call getKey() on Map.Entry<String, String> object to get the Map key and getValue() to get the value.

    // Iterate HashMap using for loop on Set<Map.Entry<String, String>>    
    import java.util.HashMap;
    import java.util.Map;
    import java.util.Set;
    	
    public class MyClass {
        public static void main(String[] args) {
            Map<String, String> map = new HashMap<String, String>();
            map.put("key1", "value1");
            map.put("key2", "value2");
            map.put("key3", "value3");
            Set<Map.Entry<String, String>> entry  = map.entrySet();
            
            for (Map.Entry<String, String> pair : entry) {
                System.out.println("key=" + pair.getKey() + "::value=" + pair.getValue());
            }
       }
    }	

    Output :

    key=key1::value=value1
    key=key2::value=value2
    key=key3::value=value3
    		

    2) Using Iterator on Map entrySet

    You can also get Iterator for the entrySet and iterate over it. This is helpful when you want to remove any entry from the HashMap using Iterator.

    // Iterate HashMap using Iterator on Set<Map.Entry<String, String>>        
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.Map;
    	
    public class MyClass {
        public static void main(String[] args) {
            Map<String, String> map = new HashMap<String, String>();
            map.put("101.102.2.3", "www.abc.com");
            map.put("101.102.2.4", "www.def.com");
            map.put("101.102.2.5", "www.ghi.com");
            
            Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, String> entry = iterator.next();
                System.out.println("key=" + entry.getKey() + "::value=" + entry.getValue());
            }
        }
    }	

    Output :

    key=101.102.2.5::value=www.ghi.com
    key=101.102.2.3::value=www.abc.com
    key=101.102.2.4::value=www.def.com		

    3) Using HashMap keySet values

    You can iterate a HashMap using for loop on Set<K> of HashMap keys. You can get Set<K> of keys by calling HashMap keySet() method. You can loop over the keySet and then use the keys to get corresponding values (by calling map.get(key)).

    The keySet is backed by original HashMap so any changes in the HashMap will be reflected in the keySet and vice-versa.

    // Iterate HashMap using for loop on Set<K> 
    import java.util.HashMap;
    import java.util.Map;
    import java.util.Set;
    	
    public class TestClass { 
     
        public static void main(String[] args) {  
          
            Map<Integer, String> map= new HashMap<>();
            map.put(1, "Apple");
            map.put(2, "Orange");
            map.put(3, "PineApple");
            Set<Integer> keySet = map.keySet();
    		
            for (Integer key : keySet) {
               System.out.println("key=" + key + "::value=" + map.get(key));
           }
        }  
    }	

    Output :

    key=1::value=Apple
    key=2::value=Orange
    key=3::value=PineApple		

    4) Using forEach loop (Java 8)

    Using Java 8 you can iterate over a HashMap by using lambda expression. HashMap forEach method will accept a BiConsumer (a functional interface) type object which can be used to iterate its keys and values. The two arguments k,v passed to BiConsumer accept(Object, Object) method represent the HashMap key and its corresponding value.

    import java.util.HashMap;
    import java.util.Map;
    	
    public class TestClass { 
     
        public static void main(String[] args) {  
          
            Map<Integer, String> map= new HashMap<>();
            map.put(1, "Apple");
            map.put(2, "Orange");
            map.put(3, "PineApple");
            map.forEach((k,v) -> System.out.println("Index [" + k + "] Fruit  [" + v + "]"));
        }  
    }
    	

    Output :

    Index [1] Fruit  [Apple]
    Index [2] Fruit  [Orange]
    Index [3] Fruit  [PineApple]		

    5) Using Stream API (Java 8)

    Using Java 8 you can also iterate over a HashMap by using Stream forEach method will accept a Consumer (a functional interface) type object which can be used to iterate its keys and values. The Entry object is passed to Consumer accept(Object) method and then you can get the HashMap key and its corresponding value by calling entry.getKey() & entry.getValue().

    import java.util.HashMap;
    import java.util.Map;
    	
    public class TestClass { 
     
        public static void main(String[] args) {  
          
            Map<Integer, String> map= new HashMap<>();
            map.put(1, "Apple");
            map.put(2, "Orange");
            map.put(3, "PineApple");
            map.entrySet().stream().forEach(entry -> System.out.println("Key : "+entry.getKey()+" Value : "+entry.getValue()));
        }  
    }
    	

    Output :

    Key : 1 Value : Apple
    Key : 2 Value : Orange
    Key : 3 Value : PineApple		

    References :

    Oracle Docs HashMap entrySet()

    Oracle Docs HashMap keySet()

    Share This