In this quick article, we’ll have a look at the different ways of iterating through the entries of a Map in Java. Simply put, we can extract the contents of a Map using keySet(), valueSet() or entrySet(). Since those are all sets, similar iteration principles apply to all of them. The Map.entrySet API returns a collection-view of the map, whose elements are from the Map class. The only way to obtain a reference to a single map entry is from the iterator of this collection view. The entry.getKey() returns the key and entry.getValue() returns the corresponding value. Let’s have a look at a few of these.
We will use following hashmap for our example:
HashMap<String, String> loans = new HashMap<String, String>();
loans.put<“home loan”, “Citibank”);
loans.put<“personal loan”, “Wells Fargo”);
1. Iterating or looping map using Java 5 foreach loop
Here we will use new foreach loop introduced in JDK5 for iterating over any map in java and using KeySet of the map for getting keys. this will iterate through all values of Map and display key and value together.
2. Iterating Map in Java using KeySet Iterator
In this Example of looping hashmap in Java we have used Java Iterator instead of for loop, rest are similar to earlier example of looping:
3. Looping HashMap in Java using EntrySet and Java 5 for loop
In this Example of traversing Map in Java, we have used EntrySet instead of KeySet. EntrySet is a collection of all Map Entries and contains both Key and Value.
4. Iterating HashMap in Java using EntrySet and Java iterator
This is the fourth and last example of looping Map and here we have used Combination of Iterator and EntrySet to display all keys and values of a Java Map.
5. Iterating with Java8’s Lambdas
6. Iterating with Java8’s Stream API
References:
One Comment
A WordPress Commenter
Hi, this is a comment.
To get started with moderating, editing, and deleting comments, please visit the Comments screen in the dashboard.
Commenter avatars come from Gravatar.