一.首先先造点我们用来测试的数据
Student student=new Student("001","sgh",99,"men");
Student student1=new Student("002","asd",100,"women");
Student student2=new Student("003","dfg",110,"men");
Student student3=new Student("004","erg",115,"men");
List<Student> studentList=new ArrayList<Student>();
studentList.add(student);
studentList.add(student1);
studentList.add(student2);
studentList.add(student3);
二、获得对象中某1个属性集合
List<Integer> scoreList= studentList.stream().map(Student::getScore).collect(Collectors.toList());
三、list转换为map集合
toMap 将List的值转成 stuNo -> name的Map
Map<String,String> studentMap= studentList.stream().collect(Collectors.toMap(Student::getStuNo,Student::getName));
四、求和、最大值、平均值
求socre最大的对象
Optional<Student> student4= studentList.stream().filter(s -> s.getScore() != null).max(Comparator.comparing(Student::getScore));
求socre的和
Integer socreSum=studentList.stream().mapToInt(Student::getScore).sum();
求平均值
Double averageSocre= studentList.stream().collect(Collectors.averagingDouble(Student::getScore));
五、去重
对数据去重
studentList.stream().distinct().collect(Collectors.toList());
根据某一属性去重
studentList.stream().collect(collectingAndThen(toCollection(() -> new TreeSet<>(Comparator.comparing(Student::getName))), ArrayList::new));
六、分组
按照性别分组并且统计数量
Map<String,Long> stringListMap=studentList.stream().collect(Collectors.groupingBy(Student::getSex,Collectors.counting()));
分组后在比较,求分组中socre最小的
Map<String,Student> stringStudentMap=studentList.stream()
.collect(Collectors.groupingBy(Student::getSex,Collectors.collectingAndThen(Collectors.minBy(Comparator.comparing(Student::getScore)),Optional::get)));
7.partitioningBy分区
按照socre>100分区,在统计
Map<Boolean,Long> booleanLongMap= studentList.stream().collect(Collectors.partitioningBy(s->s.getScore()>100,Collectors.counting()));
partitioningBy与groupingBy区别
partitioningBy函数的参数一个Predicate接口,那么这个接口的返回值是boolean类型的,也只能是boolean类型,然后他的返回值是Map的key是boolean类型,也就是这个函数的返回值只能将数据分为两组也就是ture和false两组数据。
groupingBy的函数参数为Function然后他的返回值也是Map,但是他的key是泛型,那么这个分组就会将数据分组成多个key的形式。