In this post, we are going to see How to filter a map with Java stream.
Filtering a Map
using the Java Stream API can be achieved by converting the Map
into a stream of Map.Entry objects and then apply a filter operation to select the desired entries. Here’s a complete example with an explanation and output.
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
public class MapFilterExample {
public static void main(String[] args) {
// Create a sample map
Map<Integer, String> map = new HashMap<>();
map.put(1, "Alice");
map.put(2, "Bob");
map.put(3, "Charlie");
map.put(4, "David");
map.put(5, "Eve");
// Filter the map based on a condition using Java Stream API
Map<Integer, String> filteredMap = map.entrySet()
.stream()
.filter(entry -> entry.getKey() % 2 == 0) // Keep only even keys
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
// Print the filtered map
System.out.println("Original Map: " + map);
System.out.println("Filtered Map (Even keys): " + filteredMap);
}
}
Explanation:
- We start by creating a sample
Map
namedmap
with key-value pairs. - We use the Java Stream API to filter the
map
based on a condition. In this example, we are filtering the map to keep only entries with even keys. - We call
entrySet()
on themap
to obtain a stream ofMap.Entry
objects, which represent key-value pairs. - We use the
filter
method to specify the condition for filtering. In this case, we use a lambda expression to check if the key of each entry is even (entry.getKey() % 2 == 0
). - We use the
collect
method to collect the filtered entries into a newMap
. We useCollectors.toMap
to create a newMap
with the same key-value type as the original. - Finally, we print both the original and filtered maps to see the result.
Output:
Original Map: {1=Alice, 2=Bob, 3=Charlie, 4=David, 5=Eve}
Filtered Map (Even keys): {2=Bob, 4=David}
As we can see, the Java Stream API allowed us to filter the original Map
and create a new Map
containing only the entries that met the specified condition (in this case, entries with even keys).
That’s all about How to filter a map with Java stream.
Other Java 8 tutorials.
- Difference between Anonymous Inner Class and Lambda Expression
- Java 8 Comparator comparing() example
- Java 8 Lambda Expressions Examples
- Write a program to find the nth Highest Salary using Java…
- Java 8 Functional Interface Examples
- Java 8 Supplier Examples
- Java 8 Consumer Examples
- Java 8 Predicate examples
- Java 8 default methods examples
- Java 8 Collection vs Stream
- Java 8 static methods examples
- Java 8 Method Reference Examples
- Java 8 Function interface Examples
- Java Stream filter() vs map()
- Java 8 Stream filter() examples
- Java 8 example to Collect stream into a HashMap with Lambda
- Java 8 Stream map() Examples