Java Map

By | September 29, 2021
Java Map

Introduction

Map is a very important data structure in Java. There are three types of map implementations: TreeMap, HashMap, and LinkedHashMap. A map contains a key-value pair and has methods to iterate through the map, add elements, remove elements, bulk operations, and so on. In this article, we will discuss how to iterate through HashMap elements in Java.

How to iterate over Map elements in Java (Java 8)

To do this, let’s first create a map and populate some data into it.

Map<String, String> sampleMap = new HashMap<String, String>();
sampleMap.put("1", "Jon");
sampleMap.put("2", "Sam");
sampleMap.put("3", "Mac");
sampleMap.put("4", "Ben");
System.out.println(sampleMap);

Note that the data is not sorted or ordered. Since we can get any element using the key, this is not an issue.

String name = sampleMap.get("2");
System.out.println(name);

In Java 8, iterating through Map is easy:

sampleMap.forEach((k,v)->System.out.println("key: " + k + ", value: " + v));

For each key-value pair (k,v), we are printing the value of the pair.

Vamware

The next approach is to use for loop to iterate through the map.

for (Map.Entry<String,String> entry : sampleMap.entrySet())
            System.out.println("Key = " + entry.getKey() +
                             ", Value = " + entry.getValue());

The next method is to get all the keys using the keyset() method. Same way, we can get the values using the values() method.

Vamware
    for (String roll : sampleMap.keySet())
            System.out.println("key: " + roll);

    for (String names : sampleMap.values())
            System.out.println("value: " + names);

An older approach is to get the values using an iterator and while loop. We can iterate through each element of the map and print the same.

    Iterator<Map.Entry<String, String>> itr = sampleMap.entrySet().iterator();

        while(itr.hasNext())
        {
             Map.Entry<String, String> entry = itr.next();
             System.out.println("Key = " + entry.getKey() +
                                 ", Value = " + entry.getValue());
       }

Note that we can also loop through each key of the keyset using for loop and get the value, but that is a very inefficient method and should be avoided.

Conclusion

In this article, we have discussed various ways to iterate through a map, like the forEach (action) in Java 8 and other methods like iterator, keyset(), and entrySet().

People are also reading:

Leave a Reply

Your email address will not be published.