In this tutorial, we will see “How to Filter a Map by Key & Value using Java 8 Stream API?”
Filter a Map in Java 8 with examples...!!! Click To Tweet
Example 1. Filter a Map 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 29 30 31 32 | /** * Filter Map by Key * @author Deepak Verma * */ import java.util.Map; import java.util.HashMap; import java.util.stream.Collectors; public class Filter_Map_By_Key_Java8 { public static void main(String[] args) { Map<Integer, String> studentsMap = new HashMap<Integer, String>(); studentsMap.put(43, "Yash"); studentsMap.put(98, "Sam"); studentsMap.put(61, "Gaurangee"); studentsMap.put(15, "Danny"); studentsMap.put(87, "Chris"); studentsMap.put(22, "Perry"); studentsMap.put(35, "Yashika"); studentsMap.put(58, "Lizzie"); Map<Integer, String> result = studentsMap.entrySet() .stream() .filter(x -> x.getKey().intValue() >= 40) .collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue())); System.out.println("Students who scored more than the passing threshold of 40: \n\n" + result); } } |
Output:
1 2 3 | Students who scored more than the passing threshold of 40: {98=Sam, 87=Chris, 58=Lizzie, 43=Yash, 61=Gaurangee} |
Example 2. Filter a Map by Value
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 29 30 31 32 | /** * Filter Map by Value * @author Deepak Verma * */ import java.util.Map; import java.util.HashMap; import java.util.stream.Collectors; public class Filter_Map_By_Value_Java8 { public static void main(String[] args) { Map<Integer, String> studentsMap = new HashMap<Integer, String>(); studentsMap.put(43, "Yash"); studentsMap.put(98, "Sam"); studentsMap.put(61, "Gaurangee"); studentsMap.put(15, "Danny"); studentsMap.put(87, "Chris"); studentsMap.put(22, "Perry"); studentsMap.put(35, "Yashika"); studentsMap.put(58, "Lizzie"); Map<Integer, String> result = studentsMap.entrySet() .stream() .filter(x -> (x.getValue().equals("Danny"))) .collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue())); System.out.println("Danny scored : " + result.keySet()); } } |
Output:
1 | Danny scored : [15] |
Filter a Map in Java 8 with examples...!!! Click To Tweet
Do you like this Post? – then check my other helpful posts:
Other Useful References: