Different ways to Iterate through Map in Java

Learn different ways to iterate through Map object in Java.

Image from unsplash

Let’s create a Map

Map<String , String> fruits  = new HashMap<>();
fruits.put("apple" , "🍏" );
fruits.put("banana" , "🍌" );
fruits.put("grapes", " 🍇 ");

Method 1 : Java 8 forEach method

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

Method 2: Looping by getting Entries of Map .

Set< Map.Entry<String, String> > entries = fruits.entrySet();
for(Map.Entry<String,String> entry : entries) {
   String key = entry.getKey();
String value = entry.getValue();
   System.out.println(key + " <--> " + value);
}

Note : If we use for-each loop don’t forgot to check if the Map is not null ,otherwise it will throw NullPointerException .

Method 3: Using Keys of Map in forEach loop

To get keys of the Map

Set<String> keys = fruits.keySet();
for(String key : keys) {

String value = fruits.get(key);

System.out.println(key + " <--> " + value);
}

Method 4: Using Iterator on entries of Map.

We can create iterator for entrySet of the map ,then use that to loop through each entry of the map.

Set<Map.Entry<String, String>> entries = fruits.entrySet();
Iterator<Map.Entry<String, String>> iterator = entries.iterator();
while (iterator.hasNext()){
   Map.Entry<String, String> entry = iterator.next();
   String key = entry.getKey();
   String value = entry.getValue();
   System.out.println(key + " <--> " + value);
}

If you only want keys you can get Keys by

Set<String> keys =fruits.keySet();

If you only want values of the map

Collection<String> values =  fruits.values();

Thanks for Reading 📖 . Hope you like this. If you found any typo or mistake send me a private note 📝 thanks 🙏 😊 .

Follow me JavaScript Jeep🚙💨 .

Please make a donation here. 80% of your donation is donated to someone needs food 🥘. Thanks in advance.

Other Java Articles You May Like to Explore
The 2019 Java Developer RoadMap
10 Things Java and Web Developer Should Learn in 2019
10 Testing Tools Java Developers Should Know
5 Frameworks Java Developers Should Learn in 2019
5 Courses to Learn Big Data and Apache Spark in Java
10 Courses to learn DevOps for Java Developers
10 Books Every Java Programmer Should Read
10 Tools Java Developers uses in their day-to-day work
10 Tips to become a better Java Developer

View at Medium.com

Leave a comment

Design a site like this with WordPress.com
Get started