Sunday, November 17, 2024
Google search engine
HomeLanguagesJavaHow to Iterate HashMap in Java?

How to Iterate HashMap in Java?

HashMap is a part of Java’s collection providing the basic implementation of the Map interface of Java by storing the data in (Key, Value) pairs to access them by an index of another type. One object is listed as a key (index) to another object (value). If you try to insert the duplicate key, it will replace the element of the corresponding key. In order to use this class and its methods, it is necessary to import java.util.HashMap package or its superclass.

There is a numerous number of ways to iterate over HashMap of which 5 are listed as below: 

  1. Iterate through a HashMap EntrySet using Iterators.
  2. Iterate through HashMap KeySet using Iterator.
  3. Iterate HashMap using for-each loop.
  4. Iterating through a HashMap using Lambda Expressions.
  5. Loop through a HashMap using Stream API.

Method 1: Using a for loop to iterate through a HashMap. Iterating a HashMap through a for loop to use getValue() and getKey() functions.

Implementation: In the code given below, entrySet() is used to return a set view of mapped elements. From the code given below:

  • set.getValue() to get value from the set.
  • set.getKey() to get key from the set.

Java




// Java Program to Iterate over HashMap
 
// Importing Map and HashMap classes
// from package names java.util
import java.util.HashMap;
import java.util.Map;
 
// Class for iterating HashMap using for loop
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Creating a HashMap
        Map<String, String> foodTable
            = new HashMap<String, String>();
 
        // Inserting elements to the adobe HashMap
        // Elements- Key value pairs using put() method
        foodTable.put("A", "Angular");
        foodTable.put("J", "Java");
        foodTable.put("P", "Python");
        foodTable.put("H", "Hibernate");
 
        // Iterating HashMap through for loop
        for (Map.Entry<String, String> set :
             foodTable.entrySet()) {
 
            // Printing all elements of a Map
            System.out.println(set.getKey() + " = "
                               + set.getValue());
        }
    }
}


Output

P = Python
A = Angular
H = Hibernate
J = Java

Method 2: Using a forEach to iterate through a HashMap. In the second method, the forEach function to iterate the key-value pairs.

Java




// Java Program to Iterate over HashMap
// Iterating HashMap using forEach
 
// Importing Map and HashMap classes
// from package names java.util
import java.util.HashMap;
import java.util.Map;
 
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Creating hash map
        Map<Character, String> charType
            = new HashMap<Character, String>();
 
        // Inserting data in the hash map.
        charType.put('J', "Java");
        charType.put('H', "Hibernate");
        charType.put('P', "Python");
        charType.put('A', "Angular");
 
        // Iterating HashMap through forEach and
        // Printing all. elements in a Map
        charType.forEach(
            (key, value)
                -> System.out.println(key + " = " + value));
    }
}


Output

P = Python
A = Angular
H = Hibernate
J = Java

Method 3: Using an iterator to iterate through a HashMap. In this method, iterator is being used to iterate each mapped pair in HashMap as shown in below java program.

Example:

Java




// Java Program to Iterate over HashMap
// Using Iterator
 
// Importing classes from java.util package
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
 
public class GFG {
 
    // Main driver method
    public static void main(String[] arguments)
    {
        // Creating Hash map
        Map<Integer, String> intType
            = new HashMap<Integer, String>();
 
        // Inserting data(Key-value pairs) in hashmap
        intType.put(1, "First");
        intType.put(2, "Second");
        intType.put(3, "Third");
        intType.put(4, "Fourth");
 
        // Iterator
        Iterator<Entry<Integer, String> > new_Iterator
            = intType.entrySet().iterator();
 
        // Iterating every set of entry in the HashMap
        while (new_Iterator.hasNext()) {
            Map.Entry<Integer, String> new_Map
                = (Map.Entry<Integer, String>)
                      new_Iterator.next();
 
            // Displaying HashMap
            System.out.println(new_Map.getKey() + " = "
                               + new_Map.getValue());
        }
    }
}


 
 

Output

1 = First
2 = Second
3 = Third
4 = Fourth

 Method 4: Iterating through a HashMap using Lambda Expressions

A lambda expression is a short block of code that takes in parameters and returns a value.  Lambda expressions are similar to methods, but they do not need a name, and they can be implemented right in the body of a method. The simplest lambda expression contains a single parameter and an expression:

parameter -> expression

Example: 

Java




// Iterating HashMap using Lambda Expressions- forEach()
// Importing Map and HashMap classes
// from java.util package
import java.util.HashMap;
import java.util.Map;
 
// Class
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Creating hash map
        Map<Character, String> charType
            = new HashMap<Character, String>();
 
        // Inserting elements(key-value pairs)
        // in the hash map ( Custom inputs)
        charType.put('A', "Apple");
        charType.put('B', "Basketball");
        charType.put('C', "Cat");
        charType.put('D', "Dog");
 
        // Iterating through forEach and
        // printing the elements
        charType.forEach(
            (key, value)
                -> System.out.println(key + " = " + value));
    }
}


Output

A = Apple
B = Basketball
C = Cat
D = Dog

Method 5: Loop through a HashMap using Stream API

The below example iterates over a HashMap with the help of the stream API. 

Stream API is used to process collections of objects.

Streams don’t change the original data structure, they only provide the result as per the pipelined methods

 Steps :

  • First invoke entrySet().stream() method which inturn returns Stream object.
  • Next forEach method, which iterates the input objects that are in the entrySet(). See the below code.

Example:

Java




// Java Program to Iterate over HashMap
// Loop through a HashMap using Stream API
 
// Importing classes from
// package named 'java.util'
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
 
// HashMap class
public class GFG {
 
    // Main driver method
    public static void main(String[] arguments)
    {
        // Creating hash map
        Map<Integer, String> intType
            = new HashMap<Integer, String>();
 
        // Inserting data(key-value pairs) in HashMap
        // Custom inputs
        intType.put(1, "First");
        intType.put(2, "Second");
        intType.put(3, "Third");
        intType.put(4, "Fourth");
 
        // Iterating every set of entry in the HashMap, and
        // printing all elements of it
        intType.entrySet().stream().forEach(
            input
            -> System.out.println(input.getKey() + " : "
                                  + input.getValue()));
    }
}


Output

1 : First
2 : Second
3 : Third
4 : Fourth

 

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments