Learn Java 8 streams with an example - Filter a Map by keys and values
In this section, we will learn how to filter a Map using the Stream filter() method.
Example 1: Filter Map by Keys
import java.util.HashMap;import java.util.Map;import java.util.stream.Collectors;/*Filter Map by Keys*/public class DriverClass {public static void main(String[] args) {Map<Integer, String> hMap = new HashMap<Integer, String>();hMap.put(123, "Jessie");hMap.put(234, "Alpha");hMap.put(345, "Beta");hMap.put(456, "Tesla");hMap.put(111, "Tera");Map<Integer, String> output = hMap.entrySet().stream().filter(map -> map.getKey().intValue() <= 254).collect(Collectors.toMap(map ->map.getKey(), map -> map.getValue()));System.out.println("Output: " + output);}}
Output:
Example 2: Filter Map by Values
import java.util.HashMap;import java.util.Map;import java.util.stream.Collectors;/*Filter Map by Values*/public class DriverClass {public static void main(String[] args) {Map<Integer, String> hMap = new HashMap<Integer, String>();hMap.put(123, "Tera");hMap.put(234, "Alpha");hMap.put(345, "Beta");hMap.put(456, "Tesla");hMap.put(111, "Tera");Map<Integer, String> output = hMap.entrySet().stream().filter(map -> "Tera".equals(map.getValue())).collect(Collectors.toMap(map ->map.getKey(), map -> map.getValue()));System.out.println("Output: " + output);}}
Output:
Example 3: Filter Map by both Keys and Values
import java.util.HashMap;import java.util.Map;import java.util.stream.Collectors;/*Filter Map by both Keys and Values*/public class DriverClass {public static void main(String[] args) {Map<Integer, String> hMap = new HashMap<Integer, String>();hMap.put(193, "Tera");hMap.put(234, "Alpha");hMap.put(345, "Beta");hMap.put(456, "Tesla");hMap.put(111, "Tera");Map<Integer, String> output = hMap.entrySet().stream().filter(map -> "Tera".equals(map.getValue())).filter(map ->map.getKey().intValue() <= 150).collect(Collectors.toMap(map ->map.getKey(), map -> map.getValue()));System.out.println("Output: " + output);}}
Output: