Iterate Map in java
There are different ways to iterate a map in java.
java.util.Map
is an interface. There are various implementations of Map such as HashMap
, TreeMap
, LinkedHashMap
.
All the methods outlined in this article can be used for iterating over any of these types.
Method 1: forEach() java map
Starting java 8, forEach() method is added to java.util.Map
interface. This method can be used to iterate through a hashmap.
In every iteration, it is supplied with two arguments, one is a key and another is the value of current map entry.
In the current example, we just print the key and value of the entry.
import java.util.HashMap; import java.util.Map; public class MapIterator { public static void main(String[] args) { // create a hashmap Map<Integer, String> map = new HashMap<Integer, String>(); // add values map.put(1, "mango"); map.put(2, "orange"); map.put(3, "guava"); map.forEach((key, value) -> { // print key System.out.println("Key: " + key); // print value System.out.println("Value: " + value); }); } }
forEach()
method takes an argument of type java.util.function.BiConsumer
which is a functional interface having a method which accepts two arguments.
Hence, we can supply a Lambda expression to forEach()
method with two arguments which are the key and value of a map element.
If you print both key and value in a single statement, then curly braces in lambda expression can be omitted as shown below.
map.forEach((key, value) -> System.out.println("Key: " + key + ", value= " + value));
Above code prints
Key: 1, value= mango
Key: 2, value= orange
Key: 3, value= guava
Method 2: Using entrySet()
A map stores data in key-value pairs also known as entries. These entries are instances of type java.util.Map.Entry
which is a nested interface of java.util.Map
interface.
Each entry corresponds to a map element and contains key and value for that element with methods to retrieve them(getKey()
and getValue()
) and modify them(setKey()
and setValue()
).
Entries stored in a map can be retrieved by calling entrySet()
method on the map. This set can then be iterated using a for
loop as shown below.
import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Set; public class MapIterator { public static void main(String[] args) { // create a hashmap Map<Integer, String> map = new HashMap<Integer, String>(); // add values map.put(1, "mango"); map.put(2, "orange"); map.put(3, "guava"); // get all map entries Set<Entry<Integer,String>> entrySet = map.entrySet(); // iterate over entries using a for loop for (Entry<Integer, String> entry : entrySet) { // get key and value of each entry System.out.println("Key: "+entry.getKey()); System.out.println("Value: "+entry.getValue()); } } }
Above code outputs
Key: 1
Value: mango
Key: 2
Value: orange
Key: 3
Value: guava
Note that the for loop used in this example is an enhanced for loop or a for-each loop.
Method 3: Iterator on entrySet()
As discussed above, elements of a map are stored as entries and entrySet()
method returns those entries in the form of a java.util.Set
.
This set can also be iterated using a java.util.iterator
.
A java iterator contains a hasNext()
method which returns true
if the set has an element to be iterated and a next()
method that returns the set element at the current iterator position.
When next()
is called, iterator moves on to the next element in the set. Example,
import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; public class MapIterator { public static void main(String[] args) { // create a hashmap Map<Integer, String> map = new HashMap<Integer, String>(); // add values map.put(1, "mango"); map.put(2, "orange"); map.put(3, "guava"); // get iterator over the map entries Iterator<Entry<Integer, String>> iterator = map.entrySet().iterator(); // iterate over entries using a loop while(iterator.hasNext()) { // get current map entry Entry<Integer, String> entry = iterator.next(); // get key and value of each entry System.out.println("Key: "+entry.getKey()); System.out.println("Value: "+entry.getValue()); } } }
Output of above program is
Key: 1
Value: mango
Key: 2
Value: orange
Key: 3
Value: guava
Method 4: keySet() and iterator
A map has a keySet()
method which returns a java.util.Set
of all the keys of the map. This set of keys can be iterated using a java.util.iterator
.
In every iteration, the iterator’s next()
method will return the key for a map entry. This key can be used to retrieve the corresponding value using get()
method of the map.
get()
method accepts a key for the map entry and returns the corresponding value. Example,
import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class MapIterator { public static void main(String[] args) { // create a hashmap Map<Integer, String> map = new HashMap<Integer, String>(); // add values map.put(1, "mango"); map.put(2, "orange"); map.put(3, "guava"); // get iterator over the keys of map Iterator iterator = map.keySet().iterator(); // iterate over map key while (iterator.hasNext()) { // get current map key Integer key = iterator.next(); System.out.println("Key: " + key); // get value of this key System.out.println("Value: " + map.get(key)); } } }
Remember that this method will search the entire map for the value of a key till it is found and is thus an inefficient method of iteration when compared to other methods described above.
keySet()
method, Map has a values()
method which returns a collection of values of map.Method 5: Using Stream.of() java 8
A map can also be iterated using java 8 streams.
Stream provides a static of()
method which accepts a collection and returns a stream over it.
Retrieve set of map entries using entrySet()
method which returns a java.util.Set
and pass it to Stream.of()
method.
Now, you can easily iterate over this stream using forEach()
method as shown below.
import java.util.HashMap; import java.util.Map; import java.util.stream.Stream; public class MapIterator { public static void main(String[] args) { // create a hashmap Map<Integer, String> map = new HashMap<Integer, String>(); // add values map.put(1, "mango"); map.put(2, "orange"); map.put(3, "guava"); // iterate with Stream.of Stream.of(map.entrySet()).forEach(e -> { System.out.println(e); }); } }
This code will print
Hope the article was useful.