Java 8 group by String(Java 8 按字符串分组)
问题描述
这是我的代码:
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"))
);
}
}
如何根据兴趣对学生进行分组.我尝试了以下代码:
How to group the student based on hobbies. I tried this below code:
List<Student> data = StudentData.getData();
data.stream().collect(Collectors.groupingBy(s -> s.getHobbies().stream()));
它没有给出正确的答案.
It is not giving the right answer.
推荐答案
你基本上需要一个由 Pair
组成的 Stream
(我选择 AbstractMap.SimpleEntry
这里),左边部分是爱好,右边是学生(可能反过来,没关系).
You basically need a Stream
that is made out of a Pair
(I choose AbstractMap.SimpleEntry
here) that has the left part as a Hobby and right as the Student (could be the other way around, does not matter).
稍后只需根据 Hobby
(在您的情况下为字符串)对那些进行分组.
Later just group those based on Hobby
(that is a String in your case).
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 表达式:
Entry::getKey
being a method reference that gets the key, you could write it as a lambda expression too, if it makes more sense for you:
Collectors.groupingBy(entry -> entry.getKey())
这篇关于Java 8 按字符串分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java 8 按字符串分组
基础教程推荐
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 降序排序:Java Map 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01