Learn Java 8 streams with an example - Filter a Map by keys and values

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, "Sibin");
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: {234=Alpha, 123=Sibin}


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: {123=Tera, 111=Tera}


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: {111=Tera}


More...

Comments