以下是一个示例代码,假设我们有一个Student类,其中有name、score和rank三个字段。我们需要对一组Student对象按照score字段进行排序,并给rank字段添加排名(score相同的排名也相同)。

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

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

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

    public String getName() {
        return name;
    }

    public int getScore() {
        return score;
    }

    public int getRank() {
        return rank;
    }

    public void setRank(int rank) {
        this.rank = 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("Alice", 70));
        students.add(new Student("Bob", 80));
        students.add(new Student("Cathy", 85));

        // 按score字段排序
        Collections.sort(students, new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                return o2.getScore() - o1.getScore();
            }
        });

        // 添加rank字段
        int rank = 1;
        students.get(0).setRank(1);
        for (int i = 1; i < students.size(); i++) {
            if (students.get(i).getScore() == students.get(i - 1).getScore()) {
                students.get(i).setRank(rank);
            } else {
                rank = i + 1;
                students.get(i).setRank(rank);
            }
        }

        // 输出结果
        for (Student student : students) {
            System.out.println(student.getName() + " " + student.getScore() + " " + student.getRank());
        }
    }
}

输出结果为:

Jerry 90 1
Cathy 85 2
Tom 80 3
Bob 80 3
Alice 70 5

可以看到,按照score字段排序后,Jerry排名第一,Cathy排名第二,Tom和Bob并列第三,Alice排名第五

java将对象集合中按score字段大小给另一字段rank添加排名字段score值相同的排名rank也相同

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

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