微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Java 8按字符串分组

如何解决Java 8按字符串分组

基本上Stream,您需要一个Pair(我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())
));

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

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

解决方法

这是我的代码:

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",Arrays.asList("chess","football")),new Student(3,"a3",2,Arrays.asList("running")),new Student(4,"a4",Arrays.asList("throwball",new Student(5,"a5",3,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",Arrays.asList("boxing","running")),new Student(11,"a11",9,new Student(12,"a12",11,"shuttle")),new Student(13,"a13",12,Arrays.asList("swimming"))
        );
    }

}

如何根据兴趣爱好对学生进行分组。我尝试下面的代码:

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

它没有给出正确的答案。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。