一般来说,这是如何通过它的值进行过滤的地图:
static <K, V> Map<K, V> filterByValue(Map<K, V> map, Predicate<V> predicate) {
return map.entrySet()
.stream()
.filter(entry -> predicate.test(entry.getValue()))
.collect(Collectors.toMap(Entry::getKey, Entry::getValue));
}
呼叫它是这样的:
Map<String, Integer> originalMap = new HashMap<>();
originalMap.put("One", 1);
originalMap.put("Two", 2);
originalMap.put("Three", 3);
Map<String, Integer> filteredMap = filterByValue(originalMap, value -> value == 2);
Map<String, Integer> expectedMap = new HashMap<>();
expectedMap.put("Two", 2);
assertEquals(expectedMap, filteredMap);
我不知道我的解决方案,它不工作时,我想收集它映射“e”是不t地图它只是一个对象 – Nazila
@nazila'e'是一个'Map.Entry>'。我在'collect'的调用中做了一些愚蠢的语法错误。见编辑的答案。 –
Eran
您不需要使用'filter()',只需将谓词作为参数传递给'anyMatch()'。 –