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'}]}
*/
本文来自博客园,作者:chuangzhou,转载请注明原文链接:https://www.cnblogs.com/czzz/p/17891896.html