How to Iterate over HashMap Collection in Java
Points To Remember
- A HashMap contains objects in key-value pair.
- We can use enumeration, iterator , for loop(jdk v1.5 onwards) and lamda expression( jdk v1.8)
- We can add values to HashMap using put(key,value).
- We can get all keys by .keySet() and value of a key using .get(key)
Method 1: Traverse A HashMap using "for" loop
The below example shows how we can traverse a HashMap in java using advanced for loop.import java.util.HashMap; class Test{ public static void main(String args[]){ HashMap<String, String> map = new HashMap<String, String>(); map.put("key 1","value 1"); map.put("key 2","value 2"); map.put("key 3","value 3"); map.put("key 4","value 4"); map.put("key 5","value 5"); // Iterating Map using advanced for loop available from jdk v1.5 onwards // Iterating over Values for(String value : map.values()){ System.out.println(value); } // Iterating over Keys for(String key : map.keySet()){ System.out.println(key + " " + map.get(key)); } } }
value 1 value 2 value 3 value 4 value 5 key 1 value 1 key 2 value 2 key 3 value 3 key 4 value 4 key 5 value 5
Method 2: Iterate a HashMap using Iterator
In the below method we declare an iterator "itr" and then check if the iterator has next entry element, if it has then .hasnext() returns true and itr.next() gives the next entry element.import java.util.HashMap; import java.util.Iterator; import java.util.Map; class Test{ public static void main(String args[]){ HashMap<String, String> map = new HashMap<String, String>(); map.put("key 1","value 1"); map.put("key 2","value 2"); map.put("key 3","value 3"); map.put("key 4","value 4"); map.put("key 5","value 5"); // Iterating Map using Iterator Iterator<Map.Entry<String, String>> itr = map.entrySet().iterator(); while(itr.hasNext()){ Map.Entry<String, String> entry = itr.next(); System.out.println(entry.getKey() + " " + entry.getValue()); } } }
key 1 value 1 key 2 value 2 key 3 value 3 key 4 value 4 key 5 value 5
No comments: