java list sort by multiple fields
List sorting involves the interface Comparator, the specific implementation code is as follows, taking the Apple class as an example
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;
}