Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

foreach
weakhashmap
java
communitycreator

What is the WeakHashMap.forEach() method in Java?

Programming Bytes

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.

WeakHashMap is a kind of Map that is implemented based on the HashTable. The WeakHashMap only stores WeakReference type as its keys. Once the key is no longer used, the respective mapping will automatically be removed when the garbage collection is done.

The forEach() method allows for an action to be performed on each entry of the WeakHashMap object until all entries have been processed or an exception is thrown.

Syntax

public void forEach(BiConsumer action)

Parameter

The forEach() method takes the BiConsumerRepresents a function that accepts two input arguments and returns no result function interface as a parameter. This function is executed for each entry in the WeakHashMap object.

Return value

This method doesn’t return any value.

Code

The code below demonstrates how to use the forEach() method.

import java.util.WeakHashMap;
class ForEach {
public static void main(String[] args) {
// creating a WeakHashMap
WeakHashMap<Integer, String> numbers = new WeakHashMap<>();
// inserting elemnts in the map
numbers.put(1, "One");
numbers.put(2, "Two");
numbers.put(3, "Three");
// using the forEach method
numbers.forEach( (key, value) -> {
System.out.println(key +" - " +value);
});
}
}
Using the WeakHashMap.forEach() method in Java

Explanation

  • Line 8: We create a WeakHashMap object.
  • Lines 11-13: We insert elements in the map.
  • Lines 16-18: We use the forEach() method to loop over it. We pass a lambdaLambda expressions are anonymous functions (functions without a name). We can pass the Lambda expression as a parameter to another function. We can also pass the lambda expression as an argument for the method which is expecting a functional interface as an argument. function as an argument to the forEach() method. The lambda function will get executed for each entry of the WeakHashMap object.

RELATED TAGS

foreach
weakhashmap
java
communitycreator

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