The forEach()
method in ConcurrentHashMap
is used for iteration over the entries in the map. The method takes a BiConsumer
as an argument, which is a functional interface that represents an operation that accepts two input arguments and returns no result.
Here’s an example of how to use forEach()
with a ConcurrentHashMap
:
package org.kodejava.util.concurrent;
import java.util.concurrent.ConcurrentHashMap;
public class ConcurrentHashMapForEachExample {
public static void main(String[] args) {
// Create a new ConcurrentHashMap
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
// Add some key-value pairs
map.put("One", 1);
map.put("Two", 2);
map.put("Three", 3);
map.put("Four", 4);
// Use forEach to iterate over the ConcurrentHashMap.
// The BiConsumer takes a key (k) and value (v), and we're
// just printing them here.
map.forEach((k, v) -> System.out.println("Key: " + k + ", Value: " + v));
}
}
Output:
Key: One, Value: 1
Key: Four, Value: 4
Key: Two, Value: 2
Key: Three, Value: 3
In the above example, forEach()
is used to iterate over the entries of the map
. For each entry, the key
and value
are printed. The forEach()
method is often more convenient to use than an iterator, especially when you’re only performing a single operation (like print) for each entry in the map.
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024