gpt4 book ai didi

java - 当每个对象可以分为多个组时如何对对象进行分组?

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:52:52 25 4
gpt4 key购买 nike

我有一个 List<Student>每个Student可能有多种爱好:

public class StudentData {
public static List<Student> getData() {
return Arrays.asList(
new Student(1, "a1", 1, Arrays.asList("cricket", "football", "basketball")),
new Student(2, "a2", 1, Arrays.asList("chess", "football")),
new Student(3, "a3", 2, Arrays.asList("running")),
new Student(4, "a4", 2, Arrays.asList("throwball", "football")),
new Student(5, "a5", 3, Arrays.asList("cricket", "basketball")),
new Student(6, "a6", 4, Arrays.asList("cricket")), new Student(7, "a7", 5, Arrays.asList("basketball")),
new Student(8, "a8", 6, Arrays.asList("football")),
new Student(9, "a9", 8, Arrays.asList("tennis", "swimming")),
new Student(10, "a10", 8, Arrays.asList("boxing", "running")),
new Student(11, "a11", 9, Arrays.asList("cricket", "football")),
new Student(12, "a12", 11, Arrays.asList("tennis", "shuttle")),
new Student(13, "a13", 12, Arrays.asList("swimming"))
);
}
}

如何根据爱好对学生进行分组?我试过下面的代码:

List<Student> data = StudentData.getData();
data.stream().collect(Collectors.groupingBy(s -> s.getHobbies().stream()));

它没有给出正确的答案。

最佳答案

您基本上需要一个 Stream,它由 Pair(我在这里选择 AbstractMap.SimpleEntry)组成,它的左边部分为作为学生的爱好和权利(可以反过来,没关系)。

稍后只需根据Hobby(在您的情况下是一个字符串)对这些进行分组。

data.stream()
.flatMap(student -> student.getHobbies().stream().map(hobby -> new SimpleEntry<>(hobby, student)))
.collect(Collectors.groupingBy(
Entry::getKey,
Collectors.mapping(Entry::getValue, Collectors.toList())
));

Entry::getKey 作为获取 key 的方法引用,您也可以将其编写为 lambda 表达式,如果它对您更有意义的话:

Collectors.groupingBy(entry -> entry.getKey())

关于java - 当每个对象可以分为多个组时如何对对象进行分组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50411257/

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