温馨提示×

java怎么自定义排序规则

小亿
89
2024-02-23 14:49:33
栏目: 编程语言

要自定义排序规则,可以使用Comparator接口来实现。Comparator接口包含一个compare方法,用于定义自定义排序规则。

下面是一个例子,假设有一个Student类,其中包含姓名和年龄属性,我们希望按照年龄从大到小的顺序对Student对象进行排序:

import java.util.Comparator;

public class Student {
    private String name;
    private int age;
    
    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
    
    public String getName() {
        return name;
    }
    
    public int getAge() {
        return age;
    }
}

public class AgeComparator implements Comparator<Student> {
    @Override
    public int compare(Student s1, Student s2) {
        if (s1.getAge() < s2.getAge()) {
            return 1;
        } else if (s1.getAge() > s2.getAge()) {
            return -1;
        } else {
            return 0;
        }
    }
}

然后在使用时,可以将AgeComparator传入Collections.sort方法中,这样就可以按照自定义的排序规则对Student对象进行排序:

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Student> students = new ArrayList<>();
        students.add(new Student("Alice", 20));
        students.add(new Student("Bob", 22));
        students.add(new Student("Charlie", 18));
        
        Collections.sort(students, new AgeComparator());
        
        for (Student student : students) {
            System.out.println(student.getName() + " - " + student.getAge());
        }
    }
}

运行结果将会按照年龄从大到小的顺序输出学生信息。

0