• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

8 Best ways to Iterate through HashMap in Java

July 30, 2018 by javainterviewpoint Leave a Comment

As a Java developer, everyone should know how to Iterate through HashMap, as it will be part of his routine programming. Unlike other Collections, we cannot iterate through HashMap directly we need to get the keySet or entrySet to iterate.

In this article, we will learn about all the different ways of iterating a HashMap in Java.

8 Best ways to Iterate through HashMap in Java

Method 1. Iterate through a HashMap EntrySet using Iterator

Map interface didn’t extend a Collection interface and hence it will not have its own iterator. entrySet() returns a Set and a Set interface which extends the Collection interface and now on top of it, we can use the Iterator. 

Now we can get the key-value pair easily using the getKey() and getValue() method.

package com.javainterviewpoint.iterate;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class IterateHashMap1
{
    public static void main(String[] args)
    {
        HashMap<String,String> hm = new HashMap<>();
        
        hm.put("Cricket", "Sachin");
        hm.put("Football", "Zidane");
        hm.put("Tennis", "Federer");
        
        Iterator<Map.Entry<String, String>> entrySet = hm.entrySet().iterator();
        
        while (entrySet.hasNext())
        {
            Map.Entry<String, String> entry = entrySet.next();
            
            System.out.println("Key : "+entry.getKey()+"   Value : "+entry.getValue());
        }
    }
}

Method 2. Iterate through HashMap KeySet using Iterator

The keySet() method returns the Set of all the Keys in the HashMap. Since it is a Set again we can use the Iterator to iterate it.

package com.javainterviewpoint.iterate;

import java.util.HashMap;
import java.util.Iterator;

public class IterateHashMap2
{
    public static void main(String[] args)
    {
        HashMap<String,String> hm = new HashMap<>();
        
        hm.put("Cricket", "Sachin");
        hm.put("Football", "Zidane");
        hm.put("Tennis", "Federer");
        
        Iterator keySetIterator = hm.keySet().iterator();
        
        while (keySetIterator.hasNext())
        {
            String key = keySetIterator.next();
            
            System.out.println("Key : "+key+"   Value : "+hm.get(key));
        }
    }
}

Method 3. Iterate HashMap using For-each Loop

The For-Each loop is available for all the classes which implement the Iterable interface. entrySet() method returns Set interface, Set interface extends the Collection interface which in turn extends the Iterable Interface.

The for-each loop (or) enhanced for loop in Java will invoke the iterator() method internally.

package com.javainterviewpoint.iterate;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class IterateHashMap3
{
    public static void main(String[] args)
    {
        HashMap<String,String> hm = new HashMap<>();
        
        hm.put("Cricket", "Sachin");
        hm.put("Football", "Zidane");
        hm.put("Tennis", "Federer");
        
        Set<Map.Entry<String, String>> entrySet = hm.entrySet();
        
        for(Map.Entry<String, String> entry : entrySet)
        {
            System.out.println("Key : "+entry.getKey()+"   Value : "+entry.getValue());
        }
    }
}

Method 4. Iterate a HashMap using For-each Loop [KeySet]

package com.javainterviewpoint.iterate;

import java.util.HashMap;
import java.util.Set;

public class IterateHashMap4
{
    public static void main(String[] args)
    {
        HashMap<String,String> hm = new HashMap<>();
        
        hm.put("Cricket", "Sachin");
        hm.put("Football", "Zidane");
        hm.put("Tennis", "Federer");
        
        Set<String> keySet = hm.keySet();
        
        for(String key : keySet)
        {
            System.out.println("Key : "+key+"   Value : "+hm.get(key));
        }
    }
}

Method 5. Iterating through a HashMap using Lambda Expressions

The forEach() method of the HashMap takes up the BiConsumer functional interface as the argument and hence we can pass it a lambda expression that takes two inputs as argument key and value

package com.javainterviewpoint.iterate;

import java.util.HashMap;

public class IterateHashMap5
{
    public static void main(String[] args)
    {
        HashMap<String,String> hm = new HashMap<>();
        
        hm.put("Cricket", "Sachin");
        hm.put("Football", "Zidane");
        hm.put("Tennis", "Federer");
        
        hm.forEach((k,v) -> {System.out.println("Key : "+k+"   Value : "+v);});
    }
}

We can also use map.entrySet().forEach() which belongs to the Iterable interface, it takes up Consumer Functional Interface as the argument.

package com.javainterviewpoint.iterate;

import java.util.HashMap;

public class IterateHashMap6
{
    public static void main(String[] args)
    {
        HashMap<String,String> hm = new HashMap<>();
        
        hm.put("Cricket", "Sachin");
        hm.put("Football", "Zidane");
        hm.put("Tennis", "Federer");
        
        hm.entrySet().forEach((entry) -> 
            {System.out.println("Key : "+entry.getKey()+"   Value : "+entry.getValue());});
    }
}

Method 6. Loop through a HashMap using Stream API

The Stream represents a sequence of elements from a source, the source can be a Collection or array which can provide data to a Stream.

In the below code we will get EntrySet from the entrySet() method, from the entrySet we will get the Stream through the stream() method which we will be iterating using forEach(). The entry reference will be further passed to a lambda

package com.javainterviewpoint.iterate;

import java.util.HashMap;

public class IterateHashMap7
{
    public static void main(String[] args)
    {
        HashMap<String,String> hm = new HashMap<>();
        
        hm.put("Cricket", "Sachin");
        hm.put("Football", "Zidane");
        hm.put("Tennis", "Federer");
        
        hm.entrySet().stream().forEach
            (entry-> System.out.println("Key : "+entry.getKey()+"   Value : "+entry.getValue()));
    }
}

Method 7. Using Stream of() method

We will be converting a HashMap into a Stream using the Stream.of() method, on top which we can use the forEach() method to iterate.

package com.javainterviewpoint.iterate;

import java.util.HashMap;
import java.util.stream.Stream;

public class IterateHashMap8
{
    public static void main(String[] args)
    {
        HashMap<String,String> hm = new HashMap<>();
        
        hm.put("Cricket", "Sachin");
        hm.put("Football", "Zidane");
        hm.put("Tennis", "Federer");
        
        Stream.of(hm.entrySet())
            .forEach((entry) ->{System.out.println(entry);});
    }
}

Method 8. Iterate a HashMap using Iterator.forEachRemaining() method

The forEachRemaining() method is newly added to Iterator interface in Java 8. As we have seen it earlier we can get the iterator of a Map through a Set [entrySet()]

package com.javainterviewpoint.iterate;

import java.util.HashMap;

public class IterateHashMap9
{
    public static void main(String[] args)
    {
        HashMap<String,String> hm = new HashMap<>();
        
        hm.put("Cricket", "Sachin");
        hm.put("Football", "Zidane");
        hm.put("Tennis", "Federer");
        
        hm.entrySet().iterator().forEachRemaining(entry-> 
            System.out.println("Key : "+entry.getKey()+"   Value : "+entry.getValue()));
    }
}

Other interesting articles which you may like …

  • Java 8 – Lambda Expressions
  • Java 8 – ForEach Example
  • Java 8 Default Methods in Interface
  • Multiple Inheritance in Java 8 through Interface
  • Java 9 – jdeprscan
  • Private Methods in Interfaces Java 9
  • Java Method Overloading Example
  • Java Constructor Overloading Example
  • Java this keyword | Core Java Tutorial
  • Java super keyword
  • Abstract Class in Java
  • Interface in Java and Uses of Interface in Java
  • What is Marker Interface
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • Java Autoboxing and Unboxing Examples
  • Use of Java Transient Keyword – Serailization Example
  • Use of static Keyword in Java
  • What is Method Overriding in Java
  • Encapsulation in Java with Example
  • Constructor in Java and Types of Constructors in Java
  • Final Keyword in Java | Java Tutorial
  • Java Static Import
  • Java – How System.out.println() really work?
  • Java Ternary operator
  • Java newInstance() method

Filed Under: Core Java, Java, Java Interview Tagged With: Iterate HashMap, Iterate through HashMap, iterating HashMap, Loop through HashMap

Leave a Reply Cancel reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2021 · Java Interview Point - All Rights Are Reserved ·