There are generally five ways of iterating over a Map in Java. In this article, we will discuss all of them and also look at their advantages and disadvantages.
First of all, we cannot iterate a Map directly using iterators, because Map are not Collection. Also before going further, you must know a little-bit about Map.Entry<K, V> interface.
Since all maps in Java implement Map interface, following techniques will work for any map implementation (HashMap, TreeMap, LinkedHashMap, Hashtable, etc.)
- Iterating over Map.entrySet() using For-Each loop :
Map.entrySet() method returns a collection-view(Set<Map.Entry<K, V>>) of the mappings contained in this map. So we can iterate over key-value pair using getKey() and getValue() methods of Map.Entry<K, V>. This method is most common and should be used if you need both map keys and values in the loop. Below is the java program to demonstrate it.
// Java program to demonstrate iteration over// Map.entrySet() entries using for-each loopimportjava.util.Map;importjava.util.HashMap;classIterationDemo{publicstaticvoidmain(String[] arg){Map<String,String> gfg =newHashMap<String,String>();// enter name/url pairgfg.put("GFG","geeksforgeeks.org");gfg.put("Practice","practice.geeksforgeeks.org");gfg.put("Code","code.geeksforgeeks.org");gfg.put("Quiz","quiz.geeksforgeeks.org");// using for-each loop for iteration over Map.entrySet()for(Map.Entry<String,String> entry : gfg.entrySet())System.out.println("Key = "+ entry.getKey() +", Value = "+ entry.getValue());}}chevron_rightfilter_noneOutput:
Key = Quiz, Value = quiz.geeksforgeeks.org Key = Practice, Value = practice.geeksforgeeks.org Key = GFG, Value = geeksforgeeks.org Key = Code, Value = code.geeksforgeeks.org
- Iterating over keys or values using keySet() and values() methods
Map.keySet() method returns a Set view of the keys contained in this map and Map.values() method returns a collection-view of the values contained in this map. So If you need only keys or values from the map, you can iterate over keySet or values using for-each loops. Below is the java program to demonstrate it.// Java program to demonstrate iteration over// Map using keySet() and values() methodsimportjava.util.Map;importjava.util.HashMap;classIterationDemo{publicstaticvoidmain(String[] arg){Map<String,String> gfg =newHashMap<String,String>();// enter name/url pairgfg.put("GFG","geeksforgeeks.org");gfg.put("Practice","practice.geeksforgeeks.org");gfg.put("Code","code.geeksforgeeks.org");gfg.put("Quiz","quiz.geeksforgeeks.org");// using keySet() for iteration over keysfor(String name : gfg.keySet())System.out.println("key: "+ name);// using values() for iteration over keysfor(String url : gfg.values())System.out.println("value: "+ url);}}chevron_rightfilter_noneOutput:
key: Quiz key: Practice key: GFG key: Code value: quiz.geeksforgeeks.org value: practice.geeksforgeeks.org value: geeksforgeeks.org value: code.geeksforgeeks.org
- Iterating using iterators over Map.Entry<K, V>
This method is somewhat similar to first one. In first method we use for-each loop over Map.Entry<K, V>, but here we use iterators. Using iterators over Map.Entry<K, V> has it’s own advantage,i.e. we can remove entries from the map during iteration by calling iterator.remove() method.// Java program to demonstrate iteration over// Map using keySet() and values() methodsimportjava.util.Map;importjava.util.HashMap;importjava.util.Iterator;classIterationDemo{publicstaticvoidmain(String[] arg){Map<String,String> gfg =newHashMap<String,String>();// enter name/url pairgfg.put("GFG","geeksforgeeks.org");gfg.put("Practice","practice.geeksforgeeks.org");gfg.put("Code","code.geeksforgeeks.org");gfg.put("Quiz","quiz.geeksforgeeks.org");// using iteratorsIterator<Map.Entry<String, String>> itr = gfg.entrySet().iterator();while(itr.hasNext()){Map.Entry<String, String> entry = itr.next();System.out.println("Key = "+ entry.getKey() +", Value = "+ entry.getValue());}}}chevron_rightfilter_noneOutput :
Key = Quiz, Value = quiz.geeksforgeeks.org Key = Practice, Value = practice.geeksforgeeks.org Key = GFG, Value = geeksforgeeks.org Key = Code, Value = code.geeksforgeeks.org
- Using forEach(action) method :
In Java 8, you can iterate a map using Map.forEach(action) method and using lambda expression. This technique is clean and fast.// Java code illustrating iteration// over map using forEach(action) methodimportjava.util.Map;importjava.util.HashMap;classIterationDemo{publicstaticvoidmain(String[] arg){Map<String,String> gfg =newHashMap<String,String>();// enter name/url pairgfg.put("GFG","geeksforgeeks.org");gfg.put("Practice","practice.geeksforgeeks.org");gfg.put("Code","code.geeksforgeeks.org");gfg.put("Quiz","quiz.geeksforgeeks.org");// forEach(action) method to iterate mapgfg.forEach((k,v) -> System.out.println("Key = "+ k +", Value = "+ v));}}chevron_rightfilter_noneOutput :
Key = Quiz, Value = quiz.geeksforgeeks.org Key = Practice, Value = practice.geeksforgeeks.org Key = GFG, Value = geeksforgeeks.org Key = Code, Value = code.geeksforgeeks.org
- Iterating over keys and searching for values (inefficient)
Here first we loop over keys(using Map.keySet() method) and then search for value(using Map.get(key) method) for each key.This method is not used in practice as it is pretty slow and inefficient as getting values by a key might be time-consuming.// Java program to demonstrate iteration// over keys and searching for valuesimportjava.util.Map;importjava.util.HashMap;classIterationDemo{publicstaticvoidmain(String[] arg){Map<String,String> gfg =newHashMap<String,String>();// enter name/url pairgfg.put("GFG","geeksforgeeks.org");gfg.put("Practice","practice.geeksforgeeks.org");gfg.put("Code","code.geeksforgeeks.org");gfg.put("Quiz","quiz.geeksforgeeks.org");// looping over keysfor(String name : gfg.keySet()){// search for valueString url = gfg.get(name);System.out.println("Key = "+ name +", Value = "+ url);}}}chevron_rightfilter_noneOutput :
Key = Quiz, Value = quiz.geeksforgeeks.org Key = Practice, Value = practice.geeksforgeeks.org Key = GFG, Value = geeksforgeeks.org Key = Code, Value = code.geeksforgeeks.org
References : Stackoverflow
This article is contributed by Gaurav Miglani and Abhishek Verma. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.
Recommended Posts:
- Program to Iterate over a Stream with Indices in Java 8
- Stream iterate(T,Predicate,UnaryOperator) method in Java with examples
- How to iterate over a TreeMap in Java?
- How to iterate over a 2D list (list of lists) in Java
- Java Program to Iterate Over Arrays Using for and foreach Loop
- Initialize a static Map using Java 9 Map.of()
- Map Interface in Java
- Factory method to create immutable Map in Java 9
- Map.Entry interface in Java with example
- Map Values() Method in Java With Examples
- IntStream map(IntUnaryOperator mapper) in Java
- Stream map() in Java with examples
- DoubleStream map(DoubleUnaryOperator mapper) in Java
- LongStream map(LongUnaryOperator mapper) in Java
- Immutable Map in Java
- EnumMap putAll(map) Method in Java
- Program to convert a Map to a Stream in Java
- Program to Convert List to Map in Java
- Sort elements by frequency | Set 5 (using Java Map)
- Replace null values with default value in Java Map

