Java/J2EE and SOA (349 Blogs) Become a Certified Professional
AWS Global Infrastructure

Programming & Frameworks

Topics Covered
  • C Programming and Data Structures (16 Blogs)
  • Comprehensive Java Course (5 Blogs)
  • Java/J2EE and SOA (346 Blogs)
  • Spring Framework (8 Blogs)
SEE MORE

How to Iterate Maps in Java?

Last updated on Jun 17,2021 12.4K Views

16 / 22 Blog from Java Collections

In this blog on “iterate Maps in Java”, you will be learning about various ways of iterating Maps and will analyze the methods so that it is easier for you to make a choice among them according to your requirements. The blog consists of the following topics:

Table of Content

Before starting with the methods to iterate Maps, let us first have a brief look at what is a Map in Java.

What is a Map in JAVA?

A Map is one of the most important Data Structures in Java. The Java Map interface, java.util.Map, represents the mapping between a key and a value i.e. a Java Map can store pairs of keys and values where each key is linked to a specific value. Once stored in a Map, you can later look up a particular value by using just the key of assigned to that value. Each key can be mapped to at most one value. We cannot iterate a Map directly using iterators, because Map is not Collection so we use some other ways to iterate Maps which are described in detail further in this blog.

Iterate Maps in Java
Let us have a look at the different ways to iterate Maps in Java.

Iterating over entries using For-Each loop

This method is helpful when the number of entries is not known.

</pre>
// { autofold
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class Main {

public static void main(String[] args) {
// }

Map<Integer, String> customers = new HashMap<>();
customers.put(1, "Ajay");
customers.put(2, "Barkha");
customers.put(3, "Cathy");

System.out.println("Using foreach");
customers.forEach((id, name) -> {
System.out.println("Key : " + id + " value : " + name);
});


//{ autofold
}

}
//}
<pre>

OUTPUT

Using foreach
Key : 1 value : Ajay
Key : 2 value : Barkha
Key : 3 value : Cathy

Iterating over keys or values using keySet() and values() method using for-each loop

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 the Map. So, when only keys or values from the Map is required, you can iterate over keySet or values using for-each loops.

import java.util.Map; 
import java.util.HashMap; 
   
class IterationDemo  
{ 
    public static void main(String[] arg) 
    { 
        Map<String,String> xyz = new HashMap<String,String>(); 
        
       //Enter value and url
        xyz.put("xyz", "Alphabet.org"); 
        xyz.put("Pronounce", "words.org"); 
           
        // using keySet() for iteration over keys 
        for (String name : xyz.keySet())  
            System.out.println("key: " + name); 
           
        // using values() for iteration over keys 
        for (String url : xyz.values())  
            System.out.println("value: " + url); 
    } 
}

OUTPUT
Key: pronounce
Key: xyz
Value: words.org
Value: Alphabet.org

Iterating Maps in Java: using stream() in JAVA 8

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
 
public class Main {
 
public static void main(String[] args) {
// }
 
        Map<Integer, String> students = new HashMap<>();
        students.put(1, "Anamika");
        students.put(2, "Bhaskar");
        students.put(3, "Rahul");
 
        System.out.println("");
        students.entrySet().stream().forEach(e ->
                System.out.println("Key : " + e.getKey() + " value : " + e.getValue())
        );
 
}
//}

 

OUTPUT

Key : 1 value : Anamika
Key : 2 value : Bhaskar
Key : 3 value : Rahul

Using entrySet()

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
 
public class Main {
 
public static void main(String[] args) {
// }
 
    Map<Integer, String> students = new HashMap<>();
        students.put(1, "Anamika");
        students.put(2, "Bob");
        customers.put(3, "Mary");
 
    for (Map.Entry<Integer, String> entry : students.entrySet()) {
      System.out.println("Key : " + entry.getKey() + " value : " + entry.getValue());
    }
 
 
}
//}

OUTPUT
Key : 1 value : Anamika
Key : 2 value : Bob
Key : 3 value : Mary

Using Iterator through Map

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
 
public class Main {
 
public static void main(String[] args) {
// }
 
    Map<Integer, String> Students = new HashMap<>();
        Students.put(1, "Anamika");
        Students.put(2, "Bob");
        Students.put(3, "Mary");
 
        Iterator<Map.Entry>Integer, String>> iterator = Students.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry entry = iterator.next();
            System.out.println("Key : " + entry.getKey() + " value : " + entry.getValue());
        }
//{ autofold
}
 
}
//}

OUTPUT
Key : 1 value : Anamika
Key : 2 value : Bob
Key : 3 value : Mary

After going through all these methods, you might now be in a position to choose your method according to the requirements. And with this, we come to an end of this blog on “iterate Maps in Java”. I hope the article helped you.

If you wish to learn more about Java, check out the Java training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. Edureka’s Java J2EE and SOA training and certification course is designed for students and professionals who want to be a Java Developer. The course is designed to give you a head start into Java programming and train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.

Got a question for us? Please mention it in the comments section of this blog and we will get back to you as soon as possible.

Upcoming Batches For Java Course Online
Course NameDateDetails
Java Course Online

Class Starts on 1st March,2025

1st March

SAT&SUN (Weekend Batch)
View Details
Comments
0 Comments

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

How to Iterate Maps in Java?

edureka.co