Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java

What is the forEach() method of the HashMap class in Java?

Talha Ashar

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The forEach() method of the HashMap class in Java performs a particular action on each mapping in a Hashmap instance.

The process is illustrated below:

To use the forEach() method, you will need to import the HashMap class into the program, as shown below:

import java.util.HashMap;

The prototype of the forEach() method is shown below:

public forEach(BiConsumer<K, V> action)

Parameters

The forEach() method takes a single mandatory parameter, i.e., the action to perform on each mapping.

Return value

The forEach() method returns no value.

Example

The code below shows how the forEach() method works in Java:

import java.util.HashMap;
class Main {
public static void main(String[] args)
{
// initializing HashMap
HashMap<String, Integer> quantities = new HashMap<>();
// populating HashMap
quantities.put("Apples", 10);
quantities.put("Bananas", 2);
quantities.put("Oranges", 5);
// original quantities
System.out.println("The original quantities are: " + quantities);
// double all quantities
quantities.forEach((k, v) -> {
v = v * 2;
quantities.replace(k, v);
});
// new quantities
System.out.println("The new quantities are: " + quantities);
}
}

Explanation

First, a HashMap object quantities is initialized.

Next, key-value pairs are inserted into the HashMap. All entries have unique values.

The forEach() method in line 1818 proceeds to iterate over each mapping in the HashMap and doubles each value. The replace() method updates the HashMap with the new value for a specified key. Since the replace() method is nested within the forEach() method, every key in the HashMap has its value updated. The updated quantities are then output.

RELATED TAGS

java

CONTRIBUTOR

Talha Ashar
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring