List 进行排序的方法

1,首先来看对实体对象list进行排序

List<Peson> pesonList = new ArrayList<>();
        Peson peson = new Peson();
        peson.setXiao("98.9%");
        peson.setKnag("kag");
        peson.setAge(1);

        Peson peson1 = new Peson();
        peson1.setXiao("97.9%");
        peson1.setKnag("kag");
        peson1.setAge(2);

        Peson peson2 = new Peson();
        peson2.setXiao("99.9%");
        peson2.setKnag("kag");
        peson2.setAge(3);

        Peson peson3 = new Peson();
        peson3.setXiao("99.9%");
        peson3.setKnag("kag");
        peson3.setAge(3);

        pesonList.add(peson);
        pesonList.add(peson1);
        pesonList.add(peson2);
        pesonList.add(peson3);
        System.out.println("排序前->"+pesonList);
       pesonList.sort(((o1, o2) -> {
           Double d1 = Double.parseDouble(o1.getXiao().split("%")[0]);
           Double d2 = Double.parseDouble(o2.getXiao().split("%")[0]);
           //降序
           return d2.compareTo(d1);
           //升序
           return d1.compareTo(d2);
       }));
        System.out.println("排序后->"+pesonList);
    }

  2.Collections.sort() 进行排序

//升序排列
Collections.sort(list, new Comparator<Student>() {
    public int compare(Student s1, Student s2) {
        return s1.getAge().compareTo(s2.getAge());
    }
});

//降序排列
Collections.sort(list, new Comparator<Student>() {
    public int compare(Student s1, Student s2) {
        return s2.getAge().compareTo(s1.getAge());
    }
});

//多条件-先年龄升序、后分数升序
Collections.sort(list, new Comparator<Student>() {
    public int compare(Student s1, Student s2) {
        int i = s1.getAge().compareTo(s2.getAge());
        if(i == 0) {
            i = s1.getScore().compareTo(s2.getScore());
        }
        return i;
    }
});

//日期集合List<Date> list = new ArrayList<>();
Collections.sort(list, new Comparator<Date>() {
    public int compare(Date s1, Date s2) {
        return s1.compareTo(s2);
    }
});

  3.使用JDK8新特性 list.stream():

//升序排列
list = list.stream().sorted(Comparator.comparing(Student::getAge)).collect(Collectors.toList());
list = list.stream().sorted(Comparator.comparingInt(Student::getAge)).collect(Collectors.toList());
//使用lambda表达式
list = list.stream().sorted(Comparator.comparing(e -> e.getAge())).collect(Collectors.toList());
//降序排列
list = list.stream().sorted(Comparator.comparing(Student::getAge).reversed()).collect(Collectors.toList());
//多条件-先年龄升序、后分数升序
list = list.stream().sorted(Comparator.comparing(Student::getAge).thenComparing(Comparator.comparing(Student::getScore))).collect(Collectors.toList());

  

posted @ 2023-03-23 16:11  张亮java  阅读(186)  评论(0编辑  收藏  举报