Java Hashmap forEach() Method

hashmap-forEach-method

What is a Hashmap?

Hashmap class is a part of java.util package. In Java everything is based on classes and objects. hashmap key/value pairs can be stored , but no duplicate key is allowed.If a duplicate key is inserted it will replace the present value with the new value. Many built-in methods are there in hashmap class which makes it easy to perform operations on them, like insertion , deletion and many more. One of those methods is Java Hashmap forEach() Method. 

To know more about Hashmap forEach() Method read the complete article.

Java Hashmap forEach() Method

The hashmap forEach() method is used to make a change or perform a action on each pair of key/value present in the hashmap. Below in this page you can find it’s syntax, return values, parameters with detailed examples.

Syntax :

new_hashmap.forEach(biConsumer(K,V) Action);

Return values :

This method does not returns any values.
Java-hashmap-forEach-method

Hashmap forEach() Method Example

Example :

Run
import java.util.*;

public class Main
{
  public static void main (String[]args)
  {

    // Creating an empty HashMap
    HashMap < String, Integer > hash_map_1 =
      new HashMap < String, Integer > ();


    // Mapping string values to int keys in a empty hashmap
    hash_map_1.put ("Java", 10);
    hash_map_1.put ("Hashmap", 20);
    hash_map_1.put ("forEach", 30);
    hash_map_1.put ("Method", 40);

    System.out.println ("Original hashmap : " + hash_map_1);

    hash_map_1.forEach ((key, value)->
			{
			value = value * value;
			System.out.println ("Key : " + key + " , value : " + value);
			}
			);

  }
}


Output :

Original hashmap : {Java=10, Hashmap=20, forEach=30, Method=40}
Key : Java , value : 100
Key : Hashmap , value : 400
Key : forEach , value : 900
Key : Method , value : 1600

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription