JAVA--通过Comparator比较数组

169 阅读1分钟

Comparator的 compare()会传入两个对象,如果o1顺序上小于o2则返回小于0的值,顺序相等则返回0,顺序上o1大于o2则返回大于0的值。在这个范例中,由于 string本身就是 Comparable,所以将 compareto()返回的值乘上-1,就可以调换排列顺序。

public class Test {
    public static void main(String[] args) {
        List<Student> ts = new ArrayList<Student>();
        Student s1 = new Student("x施",25);
        Student s2 = new Student("w昭君",30);
        Student s3 = new Student("d蝉",30);
        Student s4 = new Student("w玉环",45);
        ts.add(s1);
        ts.add(s2);
        ts.add(s3);
        ts.add(s4);
        ts.sort((c1,c2)->{
            //年龄升序,等年龄相同,则姓名升序
            System.out.println("---------年龄升序,等年龄相同,则姓名升序");
            int num =  c1.getAge() -c2.getAge();
            if (num == 0){
              return   c1.getName().compareTo(c2.getName());
            }return num;
        });
        ts.forEach(System.out::println);

        System.out.println("----------年龄降序,等年龄相同,则姓名降序");
        //年龄降序,等年龄相同,则姓名降序
        ts.sort((c1,c2)->{
            //年龄升序,等年龄相同,则姓名升序
            int num =  c2.getAge() -c1.getAge();
            if (num == 0){
                return   c2.getName().compareTo(c1.getName());
            }return num;
        });
        ts.forEach(System.out::println);
        System.out.println("c1在顺序上大于c2返回正数,期待:降序排列");
        //c1在顺序上大于c2返回正数,期待:升序排列
        ts.sort((c1,c2)->{
            if (c1.getAge() > c2.getAge()  ){
                return 1; //返回1表示o1权重大于o2权重,故o1排在o2后面,即升序
            }else {
                return -1;//返回-1表示o1权重小于o2权重,故o2排在o1后面,即升序
            }
        });
        ts.forEach(System.out::println);
    }
}