自定义机会排序

发布时间 2023-06-20 14:24:50作者: 郑某人1
public class SortTest {
    private static final List<String> technologyOrder = new ArrayList<>();
    private static final List<Student> students = new ArrayList<>();
    static {
        technologyOrder.add("DDD");
        technologyOrder.add("AAA");
        technologyOrder.add("CCC");
        technologyOrder.add("BBB");

        students.add(new Student().setName("EEE").setAge(new Random(100).nextInt()));
        students.add(new Student().setName("AAA").setAge(new Random(100).nextInt()));
        students.add(new Student().setName("BBB").setAge(new Random(100).nextInt()));
        students.add(new Student().setName("CCC").setAge(new Random(100).nextInt()));
        students.add(new Student().setName("DDD").setAge(new Random(100).nextInt()));

    }
    public static void main(String[] args) {
        setListOrder(students);

        System.out.println(students);
    }

    private static void setListOrder(List<Student> targetList) {
        // 按照 list 里的 mode 来排序 targetList
        targetList.sort(((o1, o2) -> {
            int io1 = technologyOrder.indexOf(o1.getName());
            int io2 = technologyOrder.indexOf(o2.getName());

            if (io1 != -1) {
                io1 = targetList.size() - io1;
            }
            if (io2 != -1) {
                io2 = targetList.size() - io2;
            }

            return io2 - io1;
        }));
    }
}

 

@Data
@Accessors(chain = true)
public class Student {
    private String name;
    private Integer age;
    private Integer stature;
}