java比较器自定义排序

这篇博客展示了如何使用Java的`Arrays.sort()`方法结合自定义比较器对学生对象进行排序。首先,根据ID升序排序,然后按照年龄和ID同时升序排序。代码中创建了两个比较器类`IdAscend`和`AgeIdAsecnd`,分别实现了排序逻辑。
摘要由CSDN通过智能技术生成
/**
 * @auther atton;
 * @create 2022-10-17-下午 1:56;
 */
public class Bijiaoqi {
    //学生类
    public static class Student{
        public String name;
        public int id;
        public int age;

        public Student(String name, int id, int age) {
            this.name = name;
            this.id = id;
            this.age = age;
        }

        @Override
        public String toString() {
            return "Student{" +
                    "name='" + name + '\'' +
                    ", id=" + id +
                    ", age=" + age +
                    '}';
        }
    }


    public static void main(String[] args) {
        Student s1 = new Student("A", 2, 20);
        Student s2 = new Student("B", 3, 21);
        Student s3 = new Student("C", 1, 23);
        Student s4 = new Student("D", 0, 22);
        Student s5 = new Student("D", 4, 22);
        Student s6 = new Student("D", 5, 22);
        Student[] stu = new Student[]{s1, s2, s3, s4,s5,s6};
        for(Student s : stu){
            System.out.println(s);
        }
		/*输出
		Student{name='A', id=2, age=20}
		Student{name='B', id=3, age=21}
		Student{name='C', id=1, age=23}
		Student{name='D', id=0, age=22}
		Student{name='D', id=4, age=22}
		Student{name='D', id=5, age=22}
		*/


        //id升序排序后的学生
        Arrays.sort(stu,new IdAscend());
        System.out.println("id升序排序后的");
        for(Student s : stu){
            System.out.println(s);
        }
		/*id升序排序后的
		Student{name='D', id=0, age=22}
		Student{name='C', id=1, age=23}
		Student{name='A', id=2, age=20}
		Student{name='B', id=3, age=21}
		Student{name='D', id=4, age=22}
		Student{name='D', id=5, age=22}
		*/
        //年龄和id升序排序后的学生
        Arrays.sort(stu, new AgeIdAsecnd());
        System.out.println("年龄和id升序");
        for(Student s : stu){
            System.out.println(s);
        }
        /*年龄和id升序
		Student{name='A', id=2, age=20}
		Student{name='B', id=3, age=21}
		Student{name='D', id=0, age=22}
		Student{name='D', id=4, age=22}
		Student{name='D', id=5, age=22}
		Student{name='C', id=1, age=23}
		*/
    }
    //定义id排序比较器
    public static class IdAscend implements Comparator<Student> {
        @Override
        public int compare(Student o1, Student o2) {
            return o1.id - o2.id;
        }
    }

    //定义按年龄和id排序,年龄相同时,按照id排序
    public static class AgeIdAsecnd implements Comparator<Student> {
        @Override
        public int compare(Student o1, Student o2) {
            return o1.age != o2.age ? (o1.age - o2.age) : o1.id - o2.id;
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值