Today, I show you about the Java 8 filter map example which filters a map by value and filters a map by key. Here we will use Stream filter() method to filter a Map by keys and values. The core jdk lacks the mechanics for filtering a map by Map.entry until Java 8.
Let’s begin:
Before Java 8
we can filter a map like this
1 2 3 4 5 6 |
String result = ""; for (Map.Entry<Integer, String> entry : myMap.entrySet()) { if("something".equals(entry.getValue())){ result = entry.getValue(); } } |
With Java 8
we can convert a Map.entrySet() to a stream, follow by a filter() and collect() it. We can also filter by value or key.
1 2 3 4 |
// Filter a map by value // Map -> Filter -> String String result = myMap.entrySet().stream().filter(e -> "something".equals(e.getValue())) .map(e -> e.getValue()).collect(Collectors.joining()); |
Or
1 2 3 4 |
// Filter a map by key // Map -> Filter -> Map Map<String, String> collect = myMap.entrySet().stream().filter(map -> "something".equals(map.getKey())) .collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue())); |
Java 8 Filter a Map Example
Create the demo program for filtering by value and by key.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
public class FilterMapExample { public static void main(String[] argv) { Map<String, String> myMap = new HashMap<>(); myMap.put("k1", "101"); myMap.put("k2", "50"); myMap.put("k10", "13"); myMap.put("k4", "20"); myMap.put("k3", "109"); myMap.put("k8", "78"); myMap.put("k22", "81"); // Map -> Filter -> String String result = myMap.entrySet().stream().filter(e -> "50".equals(e.getValue())) .map(e -> e.getValue()).collect(Collectors.joining()); System.out.println("The filtered result : " + result); // Map -> Filter -> Map Map<String, String> collect = myMap.entrySet().stream().filter(map -> "k10".equals(map.getKey())) .collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue())); System.out.println(collect); } } |
Output
1 2 |
The filtered result : 50 The filtered collect :{k10=13} |
That’s all about the Java 8 filter map example. You may be interested in Java 8 Stream Distinct Examples.
References
Processing Data with Java SE 8 Streams
Download the complete source code, click link below
FilterMapExample.zip (323 downloads)