Skip to content
  • Facebook
GeekCer Logo

GeekCer

The geek's Coding education and Review centre

  • Home
  • Tutorials
    • Java
    • Servlet
    • JSP
    • Python
    • C Tutorial
    • Spring
    • Spring Boot
    • MongoDB
    • Hibernate
    • Data Structure
  • General Knowledge
  • Biography
  • Grammar
  • Festival (त्योहार)
  • Interview
  • Differences
  • Important
  • Toggle search form

Home » Java » Iterate Map in Java, Map.entrySet(), Iterators, foreach Loop

  • Bhagat Singh Biography in Hindi (भगत सिंह का जीवन परिचय)
    Bhagat Singh Biography in Hindi (भगत सिंह का जीवन परिचय) Biography
  • Sawan ka Mahina : सावन का महीना का महत्व, भगवान शिव की पूजा
    Sawan ka Mahina : सावन का महीना का महत्व, भगवान शिव की पूजा Festival
  • Fundamental Rights of Indian Citizens
    Fundamental Rights of Indian Citizens | मौलिक अधिकार क्या हैं? General Knowledge
  • Ganesh Chaturthi Puja in Hindi | गणेश चतुर्थी का व्रत, महत्व, कथा
    Ganesh Chaturthi Puja in Hindi | गणेश चतुर्थी का व्रत, महत्व, कथा Festival
  • Fundamental Duties of Indian Citizens
    Fundamental Duties of Indian Citizens | 11 मौलिक कर्तव्य हिंदी में General Knowledge
  • Amitabh Bachchan biography in hindi | Family, wife, awards
    Amitabh Bachchan biography in hindi | Family, wife, awards Biography
  • Real life Inspirational Stories in Hindi | Success story in Hindi
    Real life Inspirational Stories in Hindi | Success story in Hindi Biography
  • America Independence Day : 4th July USA | USA Birthday
    America Independence Day : 4th July USA | USA Birthday General Knowledge

Iterate Map in Java, Map.entrySet(), Iterators, foreach Loop

Posted on August 14, 2021September 5, 2022 By GeekCer Education No Comments on Iterate Map in Java, Map.entrySet(), Iterators, foreach Loop
Iterate Map in Java

Iterate Map in Java: You will learn how to iterate over a Map in Java and the various iteration methods, Java Program to Iterate over a HashMap in this article. First let’s understand about Map in Java.

Map in Java stores elements in the form of key and value pairs. If the key is provided then map returns corresponding value.

The same method of iteration will work for any Map implementation, including HashMap, TreeMap, LinkedHashMap, Hashtable, etc., because all Java Maps implement the Map interface.

Table of Contents

  • 5 different ways to iterate a Map in Java
    • Iterate Map using Map.entrySet() with For-Each loop
    • Iterate Map using keySet() and values()
    • Iterate map in java Using forEach(action) method
    • Searching of keys in map
    • Iterate map in java using iterators
  • More about collection
  • Can you store a primitive data type into a collection?

5 different ways to iterate a Map in Java

There are following ways to iterate map in Java:

  • Map.entrySet() with For-Each loop
  • keySet() and values()
  • forEach(action) method
  • Searching of keys in map
  • By using iterators

Iterate Map using Map.entrySet() with For-Each loop

In this method of iteration, we use Map.Entry<K,V> in which Entry means key value pair. We get a collection-view of the map from Map.entrySet(), whose elements are in this class.

                  import java.util.Map; 
import java.util.HashMap; 
 
public class GeekCer { 
  public static void main(String[] arg) { 
    Map<String,String> map = new HashMap<String,String>(); 
      
    // Add data as key-key value pair 
    map.put("ADAMS", "CLERK"); 
    map.put("BLAKE", "MANAGER"); 
    map.put("FORD", "ANALYST"); 
    map.put("MILLER", "CLERK"); 
    map.put("TURNER", "SALESMAN");
          
    for (Map.Entry entry : map.entrySet()) {  
        System.out.println("Key = " + entry.getKey() + 
                             ", Value = " + entry.getValue());
    }
  } 
} 

Output:
Key = TURNER, Value = SALESMAN
Key = BLAKE, Value = MANAGER
Key = MILLER, Value = CLERK
Key = ADAMS, Value = CLERK
Key = FORD, Value = ANALYST

Iterate Map using keySet() and values()

In this program, we have iterated over keys using keySet() method and iterated over values using values() method. The keySet() method returns a set view of the keys contained in this map and values() method returns of the values contained in this map.

                  import java.util.Map; 
import java.util.HashMap; 
 
public class GeekCer { 
  public static void main(String[] arg) { 
    Map<String,String> map = new HashMap<String,String>(); 
      
    // Add data as key-key value pair 
    map.put("ADAMS", "CLERK"); 
    map.put("BLAKE", "MANAGER"); 
    map.put("FORD", "ANALYST"); 
    map.put("MILLER", "CLERK"); 
    map.put("TURNER", "SALESMAN");
          
    // Iteration over keys using keySet()
    for (String name : map.keySet()) {
      System.out.println("Key: " + name);
    }

    // Iteration over values using  values()
    for (String job : map.values()) {
      System.out.println("Value: " + job);
    }
  } 
} 

Output:
Key: TURNER
Key: BLAKE
Key: MILLER
Key: ADAMS
Key: FORD
Value: SALESMAN
Value: MANAGER
Value: CLERK
Value: CLERK
Value: ANALYST

Iterate map in java Using forEach(action) method

This technique available in Java 8, here we iterate a map using lambda expression and forEach(action) method.

                  import java.util.Map; 
import java.util.HashMap; 
 
public class GeekCer { 
  public static void main(String[] arg) { 
    Map<String,String> map = new HashMap<String,String>(); 
      
    // Add data as key-key value pair 
    map.put("ADAMS", "CLERK"); 
    map.put("BLAKE", "MANAGER"); 
    map.put("FORD", "ANALYST"); 
    map.put("MILLER", "CLERK"); 
    map.put("TURNER", "SALESMAN");
          
     map.forEach((key ,value) -> System.out.println("Key = "
            + key + ", Value = " + value)); 
  } 
} 

Output:
Key = TURNER, Value = SALESMAN
Key = BLAKE, Value = MANAGER
Key = MILLER, Value = CLERK
Key = ADAMS, Value = CLERK
Key = FORD, Value = ANALYST

Searching of keys in map

It a simple way of iteration, firstly we get the key from the map and by using key we get the value from the map.

                  import java.util.Map; 
import java.util.HashMap; 
 
public class GeekCer { 
  public static void main(String[] arg) { 
    Map<String,String> map = new HashMap<String,String>(); 
      
    // Add data as key-key value pair 
    map.put("ADAMS", "CLERK"); 
    map.put("BLAKE", "MANAGER"); 
    map.put("FORD", "ANALYST"); 
    map.put("MILLER", "CLERK"); 
    map.put("TURNER", "SALESMAN");
          
    for (String name : map.keySet()) {
      String job = map.get(name);
      System.out.println("Key = " + name + ", Value = " + job);
    } 
  } 
} 

Output:
Key = TURNER, Value = SALESMAN
Key = BLAKE, Value = MANAGER
Key = MILLER, Value = CLERK
Key = ADAMS, Value = CLERK
Key = FORD, Value = ANALYST

Iterate map in java using iterators

First of all, we create a iterator for the collection-view returned by the entrySet() method and using while loop we iterate the map.

                  import java.util.HashMap;
import java.util.Iterator;
import java.util.Map; 
 
public class GeekCer { 
  public static void main(String[] arg) { 
    Map<String,String> map = new HashMap<String,String>(); 
      
    // Add data as key-key value pair 
    map.put("ADAMS", "CLERK"); 
    map.put("BLAKE", "MANAGER"); 
    map.put("FORD", "ANALYST"); 
    map.put("MILLER", "CLERK"); 
    map.put("TURNER", "SALESMAN");
          
    Iterator<Map.Entry<String, String>> itr = map.entrySet().iterator();    
    while(itr.hasNext()) 
    { 
      Map.Entry<String, String> entry = itr.next(); 
      System.out.println("Key = " + entry.getKey() +  
                             ", Value = " + entry.getValue()); 
    } 
  } 
} 

Output:
Key = TURNER, Value = SALESMAN
Key = BLAKE, Value = MANAGER
Key = MILLER, Value = CLERK
Key = ADAMS, Value = CLERK
Key = FORD, Value = ANALYST

More about collection

We can not store primitive dat types in the collection objects hence map doesn’t store the primitive type of data. The main purpose of collection is to handle object only, but not primitive data types.

Can you store a primitive data type into a collection?

No, Collections store the elements in the form of object only. But you can store a primitive data in the form of object by using wrapper class concept.

Recommended Articles

  • Benefits of lambda expressions in java
  • Java Tutorials for Experienced
  • DBMS characteristics in Hindi
  • Java 8 map() function in stream

Share this:

  • Click to share on Facebook (Opens in new window)
  • Click to share on WhatsApp (Opens in new window)
  • Click to share on Twitter (Opens in new window)
  • More
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Pinterest (Opens in new window)

Also Read

Java Tags:How many ways we can iterate Map in Java?, Java Program to Iterate over a HashMap

Post navigation

Previous Post: Difference between GenericServlet and HttpServlet
Next Post: Immutable class in Java | How to create Immutable class in Java

More Related Articles

Java Learning Tutorial Java Tutorial for Advanced Learning, Buzzwords, Parts of Java Java
Loop in Java Loop in Java, Looping statements in java (for, while, do..while) Java
Java 8 interview questions and answers, Java Stream, Optional Java 8 interview questions and answers, Java Stream, Optional Important
Difference between final, finally and finalize Difference between final, finally and finalize Differences
Java Switch Case Java Switch Case : Switch fall-through, default, break, examples Java
Collections in Java Collections in Java Java

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • National Farmers Day in Hindi | राष्ट्रीय किसान दिवस पर निबंध | चौधरी चरण सिंह जयंती
  • Human rights day in Hindi: 10 दिसंबर ह्यूमन राइट्स डे
  • Unicef day is celebrated on December 11 | Speech on unicef day
  • Indian Navy Day: जल सेना दिवस कब और क्यों मनाया जाता है?
  • P V Sindhu Biography in Hindi, Badminton, State, Caste पी. वी. सिंधु जीवन परिचय, कहानी, राज्य, जाति
  • Draupadi Murmu Biography In Hindi | द्रौपदी मुर्मू की जीवनी
  • TCP/IP Model, Full Form, Layers and their Functions
    TCP/IP Model, Full Form, Layers and their Functions Networking
  • OSI Model | 7 Layers of OSI Model in Computer network
    OSI Model | 7 Layers of OSI Model in Computer network, Functions Networking
  • Similarities and difference between OSI and TCP/IP model
    OSI vs TCP/IP Model, Similarities and difference between OSI and TCP/IP model Networking
  • Difference between TCP and UDP
    Difference between TCP and UDP | TCP vs UDP examples Differences
  • IPv4 Vs IPv6 | Difference between IPv4 and IPv6
    IPv4 Vs IPv6 | Difference between IPv4 and IPv6 Differences
  • Network kya hai (नेटवर्क क्या है)
    Network kya hai (नेटवर्क क्या है) Networking
  • Difference between Internet and Intranet
    Difference between Internet and Intranet Differences
  • Java Tutorial
  • Servlet Tutorial
  • JSP Tutorial
  • Maven Tutorial
  • HTML Tutorial
  • Programs
  • Hindi/English Grammar
  • Difference Between ... and ...
  • HR Interview
  • Important Articles

Write to Us:
geekcer.code@gmail.com

  • About Us
  • Privacy and Policy
  • Disclaimer
  • Contact Us
  • Sitemap

Copyright © GeekCer 2022 All Rights reserved