The forEach()
method in the Map
interface in Java 8, allows you to iterate over each entry in the map, allowing you to use each key-value pair in some way.
Here’s a basic usage of the forEach() method:
package org.kodejava.util;
import java.util.HashMap;
import java.util.Map;
public class MapForEachExample {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("Apple", 10);
map.put("Orange", 20);
map.put("Banana", 30);
// Use the forEach method. Here, each key-value pair is printed.
map.forEach((key, value) -> System.out.println("Key: " + key + ", Value: " + value));
}
}
Output:
Key: Apple, Value: 10
Key: Orange, Value: 20
Key: Banana, Value: 30
In this example, a HashMap
is created and populated with some data. The forEach
method is then called on this map, with a lambda expression that accepts a key and a value, then prints them. The key
and value
parameters represent the current key-value pair the forEach
method is handling. In this lambda expression, they are printed to the console.
This operation is applied to each entry in the map, hence the name forEach
.
Using the forEach
method with lambda expressions has several benefits:
- Improved Readability: Traditional iteration requires creating an iterator, a
while
orfor
loop, and handling each element. WithforEach
and lambdas, you can express what you want to do with each element clearly and concisely, making the code easier to read and understand - Concurrency Safety: The
forEach
method is inherently safer to use in concurrent environments. You don’t need to worry aboutConcurrentModificationException
errors which you might get while using an Iterator and modifying the collection concurrently. - Less Boilerplate Code: The
forEach
function in combination with a lambda function provides a way to iterate over a collection with fewer lines of code compared to using iterators - Functional Programming: Lambda expressions and functional interfaces pave the way towards functional programming in Java, which allows for more expressive ways to manipulate collections.
Remember, although forEach
can make your code more concise, it does not necessarily make it faster.
- 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