Collectors.groupingBy根据一个或多个属性对集合中的项目进行分组
@Data
public class Student {
private String name;
private String sex;
private int age;
private String className;
public Student(String name,String sex,int age,String className){
this.name = name;
this.sex = sex;
this.age = age;
this.className = className;
}
}
按照性别分组
public static void main(String[] args) {
Student student1 = new Student("张三","1",10,"三班");
Student student2 = new Student("张三","1",11,"三班");
Student student3 = new Student("李四","0",12,"三班");
Student student4 = new Student("王二","0",12,"三班");
Student student5 = new Student("麻子","0",11,"三班");
List<Student> studentList = Lists.newArrayList(student1, student2, student3, student4, student5);
Map<Object, List<Student>> newList = studentList.stream().collect(Collectors.groupingBy(student -> student.getSex()));
log.info(newList.toString());
}
也可以多个属性分组,按照性别和班级
public static void main(String[] args) {
Student student1 = new Student("张三","1",10,"三班");
Student student2 = new Student("张三","1",11,"三班");
Student student3 = new Student("李四","0",12,"三班");
Student student4 = new Student("王二","0",12,"三班");
Student student5 = new Student("麻子","0",11,"三班");
List<Student> studentList = Lists.newArrayList(student1, student2, student3, student4, student5);
Map<Object, List<Student>> newList = studentList.stream().collect(Collectors.groupingBy(student -> student.getName() + ":" + student.getSex()+ ":" + student.getAge()));
log.info(newList.toString());
}
另外一个用法就是判断入参数组里面是否有重复数据 这个时候就可以用
long distinctCount = studentList.stream().collect(Collectors.groupingBy(student -> student.getName() + ":" + student.getSex()+ ":" + student.getAge()));
if (paramList.size() != distinctCount) {
throw new BizException("xxxxxx重复");
}
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有