To filter a Map using Stream and Lambda Expression in Java, we will use the filter() method of Stream object which will be retrieved from Entry object of Map object with Lambda Expression as filter a List. How is it in details? Let learn together in this tutorial.
Example, I have the following Map object as below:
1 2 3 4 |
Map<String, Integer> studentMap = new HashMap<>(); studentMap.put("Khanh", 31); studentMap.put("Thanh", 25); studentMap.put("Dung", 35); |
Before Java 8, to filter this Map and only get the age of Khanh, we can write the code as below:
1 2 3 4 5 6 |
int age = 0; for (Map.Entry<String, Integer> entry : studentMap.entrySet()) { if ("Khanh".equals(entry.getKey())) { age = entry.getValue(); } } |
Result:
Since Java 8, we can re-write this code as below:
1 2 3 4 5 6 7 |
Integer result = studentMap.entrySet().stream() .filter(map -> "Khanh".equals(map.getKey())) .map(map -> map.getValue()) .findFirst() .get(); System.out.println(result); |
Result:
Here you can also filter a Map and return a new Map as below:
1 2 3 4 5 |
Map<String, Integer> result = studentMap.entrySet().stream() .filter(map -> "Khanh".equals(map.getKey())) .collect(Collectors.toMap(m -> m.getKey(), m -> m.getValue())); System.out.println(result); |
Result: