JAVA - Collections - groupingBy

public class Test1 {

    public static void main(String[] args) {
        Student s = new Student("张三",18,"唱歌");
        Student s1 = new Student("李四",27,"跳舞");
        Student s2 = new Student("王五",26,"学习JAVA");
        Student s3 = new Student("旺财",19,"LOL");
        Student s4 = new Student("旺财",19,"唱歌");
        Student s5 = new Student("旺财",19,"学习JAVA");

        List<Student> studens = new ArrayList<Student>();
        studens.add(s);
        studens.add(s1);
        studens.add(s2);
        studens.add(s3);
        studens.add(s4);
        studens.add(s5);
        
        //根据学生的兴趣爱好分组
        Map<String, List<Student>> map =  studens.stream().collect(Collectors.groupingBy(Student::getHobby));

        System.out.println(map);
    }
}

/*
{唱歌=[Student{name='张三', age=18, hobby='唱歌'}, Student{name='旺财', age=19, hobby='唱歌'}], LOL=[Student{name='旺财', age=19, hobby='LOL'}], 跳舞=[Student{name='李四', age=27, hobby='跳舞'}], 学习JAVA=[Student{name='王五', age=26, hobby='学习JAVA'}, Student{name='旺财', age=19, hobby='学习JAVA'}]}
*/

参考:https://blog.csdn.net/HO1_K/article/details/127572093

posted @ 2023-12-09 22:09  chuangzhou  阅读(33)  评论(0编辑  收藏  举报