How does HashMap forEach() Method Work in Java 8?
Last Updated :
14 Feb, 2024
The HashMap is a part of collections in the java.util package. The HashMap in Java stores the data in the form of a key-value pair. The HashMap takes the generic parameters for the key along with the value. Similarly, like we instantiate the classes in Java we also instantiate the hash map like we create objects in Java.
In this article, we will be using the forEach() method. The forEach() method in Java iterates over the hashMap and we can perform any action on the key and values in the method.
Syntax:
hashMap.forEach( (key , value) ->
{
//action to be performed
}
);
- The forEach() method takes the parameters a key and value variable which represents the key and value pair.
- After that, we used -> which specifies that it is a lambda expression. The lambda expression specifies the action to be performed in the forEach () method.
Note: The forEach() method doesn’t have any return value.
Program to Understand forEach() Method in HashMap in Java 8
Below is the Program to Understand forEach() method in HashMap in Java 8:
Java
import java.util.*;
public class GFG {
public static void main(String args[])
{
HashMap<Integer, String> hm = new HashMap<>();
hm.put( 1 , "Krishna" );
hm.put( 2 , "Harsha" );
hm.put( 3 , "Rama" );
hm.put( 4 , "Arfan khan" );
hm.put( 5 , "Joseph" );
hm.forEach((key, value) -> {
String str = value.toUpperCase();
int keyvalue = key * 10 ;
System.out.println( "Key : " + keyvalue + " Value : " + str);
});
}
}
|
Output
Key : 10 Value : KRISHNA
Key : 20 Value : HARSHA
Key : 30 Value : RAMA
Key : 40 Value : ARFAN KHAN
Key : 50 Value : JOSEPH
Explanation of the Program:
- In the above program, we have created a HashMap with the help of the java.util package.
- The HashMap is instantiated with the object hm.
- We have used the HashMap object to use the forEach() method in the class HashMap class.
- The forEach method in the hashmap takes Biconsumer as parameters and uses lambda expression to perform some action with it.
- The HashMap created in the above program consists of key which is of string type and value which is of integer type.
- So, when we use the forEach methosd we have specified in the lambda expression to convert the key into uppercase and the value multiplied by 10.
- In this way, we can use the forEach method in the Java 8.
Share your thoughts in the comments
Please Login to comment...