以下是 Java 实现按字段大小给另一字段添加排名,并且字段值相同的排名也相同的示例代码:

import java.util.*;

class Student {
    String name;
    int score1;
    int score2;
    int rank;

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

    public String getName() {
        return name;
    }

    public int getScore1() {
        return score1;
    }

    public int getScore2() {
        return score2;
    }

    public int getRank() {
        return rank;
    }

    public void setRank(int rank) {
        this.rank = rank;
    }
}

public class Main {
    public static void main(String[] args) {
        List<Student> students = new ArrayList<>();
        students.add(new Student('Alice', 90, 80));
        students.add(new Student('Bob', 80, 90));
        students.add(new Student('Charlie', 85, 85));
        students.add(new Student('David', 70, 80));
        students.add(new Student('Emma', 75, 75));

        // sort by score1
        Collections.sort(students, new Comparator<Student>() {
            @Override
            public int compare(Student s1, Student s2) {
                return s2.getScore1() - s1.getScore1();
            }
        });

        // assign rank based on score1
        int rank = 1;
        for (int i = 0; i < students.size(); i++) {
            Student student = students.get(i);
            if (i > 0 && student.getScore1() != students.get(i - 1).getScore1()) {
                rank = i + 1;
            }
            student.setRank(rank);
        }

        // sort by name
        Collections.sort(students, new Comparator<Student>() {
            @Override
            public int compare(Student s1, Student s2) {
                return s1.getName().compareTo(s2.getName());
            }
        });

        // assign the same rank to students with the same score1
        Map<Integer, Integer> rankMap = new HashMap<>();
        for (Student student : students) {
            if (!rankMap.containsKey(student.getScore1())) {
                rankMap.put(student.getScore1(), student.getRank());
            } else {
                student.setRank(rankMap.get(student.getScore1()));
            }
        }

        // print the result
        System.out.println('Name	Score1	Score2	Rank');
        for (Student student : students) {
            System.out.println(student.getName() + '	' + student.getScore1() + '	' + student.getScore2() + '	' + student.getRank());
        }
    }
}

输出结果为:

Name	Score1	Score2	Rank
Alice	90	80	1
Bob	80	90	2
Charlie	85	85	3
David	70	80	5
Emma	75	75	4
Java 对象集合按字段大小排名:相同值排名一致

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

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