java list 按照多字段排序

java list 按照多字段排序

 

list 排序涉及的接口 Comparator, 具体实现代码如下,以Apple类为例

 

复制代码
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();
     apples.sort(byName.thenComparing(bySizeDesc));    // 先以名称升序排列,再按照size倒叙排列
  }
} @Data public class Apple{ private String color; private String name; private Integer size;
}
复制代码
posted @ 2020-04-14 14:02  GordonDicaprio  阅读(2162)  评论(0编辑  收藏