How to group objects when each object could go in multiple groups?(当每个对象可以放在多个组中时,如何对对象进行分组?)
本文介绍了当每个对象可以放在多个组中时,如何对对象进行分组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个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()));
它没有给出正确答案。
推荐答案
您基本上需要一个由Pair(我在这里选择AbstractMap.SimpleEntry)组成的Stream,它的左边部分作为业余爱好,右边部分作为学生(可以反过来,不要紧)。
稍后只需根据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作为获取键的方法引用,如果对您更有意义,您也可以将其编写为lambda表达式:
Collectors.groupingBy(entry -> entry.getKey())
这篇关于当每个对象可以放在多个组中时,如何对对象进行分组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
织梦狗教程
本文标题为:当每个对象可以放在多个组中时,如何对对象进行分组?
基础教程推荐
猜你喜欢
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
