java list 按照多字段属性排序

java | 2020-03-06 16:16:13

之前整理过java list 排序的几种方式,虽然有很多种方式,但是没有整理按多个字段排序

list 排序涉及的接口 Comparator,实现多个字段属性排序也很简单

案例代码:

public class Test{
  public static void main(String [] args){
     List<Apple> apples = new ArrayList<>();
        Comparator<Apple> byName = Comparator.comparing(Apple::getName);
        Comparator<Apple> bySizeDesc = Comparator.comparing(Apple::getSize).reversed();
     // 先以名称升序排列,再按照size倒叙排列
     apples.sort(byName.thenComparing(bySizeDesc));   
  }
}

@Data
public class Apple{
    private String color;
    private String name;
    private Integer size;
}

 

登录后即可回复 登录 | 注册
    
关注编程学问公众号