Java8 Stream之分组后,分组List再排序

Java8 Stream之分组后,分组List再排序



场景:统计所有学生的科目和分数,将学生分组后,该学生的分数倒序或正序排列

实体

import lombok.Data;

@Data
public class Student {
          
   
    /**
     * 名字
     **/
    private String name;
    /**
     * 科目
     **/
    private String project;
    /**
     * 分数
     **/
    private Integer score;
    /**
     * 创建时间
     **/
    private Date createTime;

}

通过sql查询的数据,会变为List<Student>,部分数据如下


分组排序

下面通过groupingBy(Function<? super T, ? extends K> classifier, Supplier<M> mapFactory, Collector<? super T, A, D> downstream)方法进行分组

方式一

//先分组
Map<String, List<Student>> map = list.stream().collect(
		Collectors.groupingBy(Student::getName));
//再排序
for (Map.Entry<String, List<Student>> nmap : map.entrySet()) {
          
   
   nmap.getValue().sort(Comparator.comparing(Student::getScore));
}

方式二

该方式通过collectingAndThen(Collector<T,A,R> downstream, Function<R,RR> finisher),分组完成后再排序

//分组排序
Map<String, List<Student>> map = list.stream().collect(
	Collectors.groupingBy(Student::getName, HashMap::new, 		
      Collectors.collectingAndThen(Collectors.toList(),
      //正序
	  list -> list.stream().sorted(Comparator.comparing(Student::getScore)) 
  //倒序
  //list -> list.stream().sorted(Comparator.comparing(Student::getScore).reversed()) 
	    .collect(Collectors.toList())
)));
经验分享 程序员 微信小程序 职场和发展