可以通过实现 Comparator 接口来实现按字段大小排序,并使用一个计数器来记录排名。具体实现如下:

假设有一个 Student 类,其中有两个字段 namescore,需要按 score 字段大小给 name 字段添加排名。

public class Student {
    private String name;
    private int score;
    private int rank;

    // 构造方法、getter和setter方法省略

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + "'"
                + ", score=" + score +
                ", rank=" + rank +
                '}';
    }
}

实现 Comparator 接口:

public class ScoreComparator implements Comparator<Student> {

    @Override
    public int compare(Student o1, Student o2) {
        return o2.getScore() - o1.getScore(); // 按score字段从大到小排序
    }
}

在主程序中,定义一个 List<Student> 集合,并使用 Collections.sort() 方法按 score 字段排序。然后遍历集合,给每个 Student 对象的 rank 字段赋值:

public static void main(String[] args) {
    List<Student> students = new ArrayList<>();
    students.add(new Student("Tom", 80));
    students.add(new Student("Jerry", 90));
    students.add(new Student("Mike", 70));
    students.add(new Student("Mary", 90));
    students.add(new Student("Lily", 85));

    Collections.sort(students, new ScoreComparator());

    int rank = 1;
    for (int i = 0; i < students.size(); i++) {
        Student s = students.get(i);
        s.setRank(rank);
        if (i < students.size() - 1 && s.getScore() != students.get(i + 1).getScore()) {
            rank++; // 如果下一个学生的分数不同,则排名加1
        }
    }

    for (Student s : students) {
        System.out.println(s);
    }
}

输出结果如下:

Student{name='Jerry', score=90, rank=1}
Student{name='Mary', score=90, rank=1}
Student{name='Lily', score=85, rank=3}
Student{name='Tom', score=80, rank=4}
Student{name='Mike', score=70, rank=5}
Java 对象集合按字段大小排序并添加排名

原文地址: https://www.cveoy.top/t/topic/oXfD 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录