让
class Person {
String name;
int age;
}
我的变量是
Map<Sring, List<Person>> myVariable;
我想要得到的结果是
Map<String, List<Person>> result;
条件是收集所有满足此条件的人
Predicate<Person> predicate = p -> p.age > 20;
如果 map 中的条目包含 3 个人,而其中只有 2 人满足此条件,则应删除第 3 个人
示例:myVariable =
"1": [{name: "Foo", age: 15}, {name: "Foo", age: 13}, {name: "Foo", age: 14}]
"2": [{name: "Foo", age: 15}, {name: "Foo", age: 13}, {name: "Foo", age: 14}]
"3": [{name: "Foo", age: 15}, {name: "Foo", age: 13}, {name: "Foo", age: 14}]
"4": [{name: "Foo", age: 15}, {name: "Foo", age: 21}, {name: "Foo", age: 27}]
结果=
"4": {name: "Foo", age: 21}, {name: "Foo", age: 27}]
我试过了
Map<String, List<Persin>> result = myVariable.keySet().stream()
.filter(p -> myVariable.keySet(p).stream().anyMatch(predicate))
.collect(Collectors.toMap(p -> p, myVariable.get(Function.identity()).stream().filter(predicate).collect(Collectors.toList())));
但是这不起作用。
最佳答案
您可以使用两个filter
调用:
Map<String, List<Person>> result = myVariable.entrySet().stream()
.map(entry -> Map.entry(entry.getKey(), entry.getValue()
.stream().filter(p -> p.getAge() > 20)
.collect(Collectors.toList())))
.filter(entry -> !entry.getValue().isEmpty())
.collect(Collectors.toMap(Entry::getKey, Entry::getValue));
如果您使用的是 Java 8,请将 Map.entry()
替换为 new AbstractMap.SimpleEntry()
。
关于java - 根据条件过滤并收集 Map<String, List<Object>> 为 Map<String, List<Object>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68299614/