Java 用分数进行排名,分数相同则并列排名,后面的顺延,例如:A(95),B(95),C(85)D(80),结果为A(1),B(1),C(3),D(4)
时间: 2024-02-05 10:03:01 浏览: 41
归并排序.java 使用java代码来实现
可以通过以下代码实现:
```java
import java.util.*;
public class RankScores {
public static void main(String[] args) {
Map<String, Integer> scores = new HashMap<>();
scores.put("A", 95);
scores.put("B", 95);
scores.put("C", 85);
scores.put("D", 80);
List<Map.Entry<String, Integer>> list = new ArrayList<>(scores.entrySet());
Collections.sort(list, (o1, o2) -> o2.getValue().compareTo(o1.getValue())); // 按照分数降序排序
int rank = 0;
int prevScore = -1;
for (int i = 0; i < list.size(); i++) {
Map.Entry<String, Integer> entry = list.get(i);
int score = entry.getValue();
if (score != prevScore) {
rank = i + 1;
}
System.out.println(entry.getKey() + " (" + rank + ")");
prevScore = score;
}
}
}
```
输出结果为:
```
A (1)
B (1)
C (3)
D (4)
```
阅读全文