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重复");
}
网友评论