gpt4 book ai didi

Java 8 使用流和收集器映射到集合的子列表条目

转载 作者:搜寻专家 更新时间:2023-10-31 08:18:57 25 4
gpt4 key购买 nike

我 Collection 了 Person对象:.

public class Person {

String name;

ChildrenListHolder childrenListHolder;
}

public class ChildrenListHolder {
List<Children> children;
}

public class Children {
String childrensName;
}

(实体结构由第三方给出。)

现在,我需要一个 Map<String,List<Person>> childrensName -> 人员列表

例如(简体):

Person father: {name: "John", childrensListHolder -> {"Lisa", "Jimmy"}}
Person mother: {name: "Clara", childrensListHolder -> {"Lisa", "Paul"}}
Person george: {name: "George", childrensListHold -> "Paul"}}

map ,我需要的是

Map<String, List<Person>> map: {"Lisa"  -> {father, mother},
"Jimmy" -> {father},
"Paul" -> {mother, george}}

我可以用一堆 for 和 if 来做到这一点。但是我如何使用流和收集器来做到这一点。我尝试了很多方法,但我无法得到预期的结果。 TIA。

最佳答案

给定一个 List<Person> persons , 你可以有以下内容

Map<String,List<Person>> map =
persons.stream()
.flatMap(p -> p.childrenListHolder.children.stream().map(c -> new AbstractMap.SimpleEntry<>(c, p)))
.collect(Collectors.groupingBy(
e -> e.getKey().childrensName,
Collectors.mapping(Map.Entry::getValue, Collectors.toList())
));

这是在人身上创建一个流。然后每个人都被一个包含 child 和每个 child 的人的元组平面映射。最后,我们按 child 的名字分组,并将所有的人收集到一个列表中。

假设有适当的构造函数的示例代码:

public static void main(String[] args) {
List<Person> persons = Arrays.asList(
new Person("John", new ChildrenListHolder(Arrays.asList(new Children("Lisa"), new Children("Jimmy")))),
new Person("Clara", new ChildrenListHolder(Arrays.asList(new Children("Lisa"), new Children("Paul")))),
new Person("George", new ChildrenListHolder(Arrays.asList(new Children("Paul"))))
);

Map<String,List<Person>> map =
persons.stream()
.flatMap(p -> p.childrenListHolder.children.stream().map(c -> new AbstractMap.SimpleEntry<>(c, p)))
.collect(Collectors.groupingBy(
e -> e.getKey().childrensName,
Collectors.mapping(Map.Entry::getValue, Collectors.toList())
));

System.out.println(map);
}

关于Java 8 使用流和收集器映射到集合的子列表条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36271008/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com