Java 8 group by String

Lea*_*oop 3 java grouping java-8 java-stream

这是我的代码:

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"))
        );
    }

}
Run Code Online (Sandbox Code Playgroud)

如何根据兴趣爱好对学生进行分组.我试过以下代码:

List<Student> data = StudentData.getData();
data.stream().collect(Collectors.groupingBy(s -> s.getHobbies().stream()));
Run Code Online (Sandbox Code Playgroud)

它没有给出正确的答案.

Eug*_*ene 9

你基本上需要一个StreamPair(我AbstractMap.SimpleEntry在这里选择)制作的左边部分作为爱好而右边作为学生(可能是相反的方式,无关紧要).

稍后只是将那些基于Hobby(在你的情况下是一个String)分组.

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

Entry::getKey 作为一个获取键的方法引用,你可以将它写成一个lambda表达式,如果它对你更有意义:

Collectors.groupingBy(entry -> entry.getKey())
Run Code Online (Sandbox Code Playgroud)