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)
The forEach()
method takes a single mandatory parameter, i.e., the action to perform on each mapping.
The forEach()
method returns no value.
The code below shows how the forEach()
method works in Java:
import java.util.HashMap;class Main {public static void main(String[] args){// initializing HashMapHashMap<String, Integer> quantities = new HashMap<>();// populating HashMapquantities.put("Apples", 10);quantities.put("Bananas", 2);quantities.put("Oranges", 5);// original quantitiesSystem.out.println("The original quantities are: " + quantities);// double all quantitiesquantities.forEach((k, v) -> {v = v * 2;quantities.replace(k, v);});// new quantitiesSystem.out.println("The new quantities are: " + quantities);}}
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 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.
Free Resources