1、对map按值过滤返回值
public class TestMapFilter { public static void main(String[] args) {
Map<Integer, String> HOSTING = new HashMap<>();
HOSTING.put(1, "linode.com");
HOSTING.put(2, "heroku.com");
HOSTING.put(3, "digitalocean.com");
HOSTING.put(4, "aws.amazon.com"); // Before Java 8
String result = "";
for (Map.Entry<Integer, String> entry : HOSTING.entrySet()) {
if ("heroku.com".equals(entry.getValue())) {
result = entry.getValue();
}
}
System.out.println("Before Java 8: " + result); // Map -> Stream -> Filter -> String
result = HOSTING.entrySet().stream()
.filter(map -> "linode.com".equals(map.getValue()))
.map(map -> map.getValue())
.collect(Collectors.joining());
System.out.println("With Java 8:" + result); // filter more values
result = HOSTING.entrySet().stream()
.filter(x -> {
if (!x.getValue().contains("amazon") && !x.getValue().contains("digital")) {
return true;
}
return false;
})
.map(map -> map.getValue())
.collect(Collectors.joining(",")); System.out.println("With Java 8 : " + result);
}
}
2、按key过滤返回map
public class TestMapFilter2 { public static void main(String[] args) {
Map<Integer, String> HOSTING = new HashMap<>();
HOSTING.put(1, "linode.com");
HOSTING.put(2, "heroku.com");
HOSTING.put(3, "digitalocean.com");
HOSTING.put(4, "aws.amazon.com"); //Map -> Stream -> Filter -> Map
Map<Integer, String> result1 = HOSTING.entrySet().stream()
.filter(map -> map.getKey() == 2)
.collect(Collectors.toMap(h -> h.getKey(), h -> h.getValue())); System.out.println(result1); Map<Integer, String> result2 = HOSTING.entrySet().stream()
.filter(map -> map.getKey() <= 4)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
System.out.println(result2);
}
}
3、Predicate使用
public class TestMapFilter3 { public static <K, V> Map<K, V> filterByValue(Map<K, V> map, Predicate<V> predicate) {
return map.entrySet().stream()
.filter(x -> predicate.test(x.getValue()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
} public static void main(String[] args) { Map<Integer, String> HOSTING = new HashMap<>();
HOSTING.put(1, "linode.com");
HOSTING.put(2, "heroku.com");
HOSTING.put(3, "digitalocean.com");
HOSTING.put(4, "aws.amazon.com");
HOSTING.put(5, "aws2.amazon.com"); Map<Integer, String> result1 = filterByValue(HOSTING, x -> x.contains("heroku"));
System.out.println(result1); Map<Integer, String> result2 = filterByValue(HOSTING, x -> (x.contains("aws") || x.contains("digitalocean")));
System.out.println(result2); Map<Integer, String> result3 = filterByValue(HOSTING, x -> (x.contains("aws") && !x.contains("aws2")));
System.out.println(result3); Map<Integer, String> result4 = filterByValue(HOSTING, x -> x.length() <= 10);
System.out.println(result4);
}
}