以下是一种可能的实现方法:

  1. 定义一个对象类,该类具有需要排名的字段以及排名字段(例如,需要排名的字段是'score',排名字段是'rank')。

  2. 创建一个对象集合,将需要排名的对象添加到集合中。

  3. 使用 Collections.sort() 方法对集合进行排序,根据需要排名的字段进行排序。

  4. 遍历集合,对每个对象的排名字段进行赋值。如果当前对象的需要排名的字段值和上一个对象的值相同,则排名字段值与上一个对象相同,否则排名字段值为当前对象在集合中的位置(下标)加 1。

以下是示例代码:

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

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

    // getter and setter methods

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

public class Main {
    public static void main(String[] args) {
        List<Student> students = new ArrayList<>();
        students.add(new Student("Tom", 85));
        students.add(new Student("Jerry", 70));
        students.add(new Student("Alice", 85));
        students.add(new Student("Bob", 90));
        students.add(new Student("David", 70));

        Collections.sort(students, new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                return Integer.compare(o2.getScore(), o1.getScore()); // 降序排列
            }
        });

        int rank = 1;
        for (int i = 0; i < students.size(); i++) {
            Student student = students.get(i);
            if (i > 0 && student.getScore() == students.get(i - 1).getScore()) {
                student.setRank(students.get(i - 1).getRank());
            } else {
                student.setRank(rank);
            }
            rank++;
        }

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

输出结果为:

Student [name='Bob', score='90', rank='1']
Student [name='Tom', score='85', rank='2']
Student [name='Alice', score='85', rank='2']
Student [name='Jerry', score='70', rank='4']
Student [name='David', score='70', rank='4']
Java 对象集合排序并添加排名:同分同排名

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

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