我不认为这叫做“愤怒”,但我需要做到以下几点:我有课
class Person {
String name;
Set<String> groups;
}我有一些人:
”}
G 210
因此,每个人都可以成为多个类别的一部分。我想得到以下映射:
"Worker" => {Father}
"Men" => {Father, Son}
"Student" => {Son, Daughter}
"Woman" => {Mother, Daughter}现在,我可以通过手动迭代每个人并将其放到Map<String,List<Person>>中来完成这一任务。
我正在努力寻找一种更优雅的方法来使用streams (或StreamEx) oneliner来完成它,比如:
List<Persons> family= ...;
Map<String,List<Person>> groupped = family.stream().groupByMultipleAttributes(Person::getGroups)发布于 2020-01-29 13:49:27
您可以生成所有相关的组和Person对,然后用groupingBy将它们收集到一个Map中。
Map<String,List<Person>> groups =
family.stream()
.flatMap(p -> p.getGroups()
.stream()
.map(g -> new SimpleEntry<>(g,p)))
.collect(Collectors.groupingBy(Map.Entry::getKey,
Collectors.mapping(Map.Entry::getValue,
Collectors.toList())));https://stackoverflow.com/questions/59968420
复制相似问题