java8 List按照两个属性第一个属性升序排序第二个属性降序排序
package com.spring.study.test; import java.util.ArrayList; import java.util.Comparator; import java.util.List; /** * @Description 请描述类的业务用途 * @Author DongGuo * @Date 2022/6/27 下午2:17 * @Version 1.0 **/ public class TesstSort { public static void main(String[] args) { En en1 = new En(1, 2); En en2 = new En(1, 3); En en3 = new En(2, 3); List<En> enList = new ArrayList<>(); enList.add(en1); enList.add(en2); enList.add(en3); enList.sort(Comparator.comparing(En::getId, Comparator.naturalOrder()).thenComparing(En::getId2, Comparator.reverseOrder())); System.out.println(enList); } public static class En { int id; int id2; public En(int id, int id2) { this.id = id; this.id2 = id2; } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getId2() { return id2; } public void setId2(int id2) { this.id2 = id2; } @Override public String toString() { return "En{" + "id=" + id + ", id2=" + id2 + '}'; } } }
输出结果为:
[En{id=1, id2=3}, En{id=1, id2=2}, En{id=2, id2=3}]
郭慕荣博客园