总分数排名,连续排序和同分数同名次排序(lambda表达式整数倒序scores.sort(Comparator.reverseOrder());)
统计排序,同分数同排名,连续排名和同分数同名次排序(lambda表达式整数倒序),同分同名间断排名
import org.springframework.util.CollectionUtils;
import java.util.*;
public class Rank {
public static void main(String[] args) {
List<Integer> scores = Arrays.asList(320, 321, 321, 300, 288, 288, 287);
if (CollectionUtils.isEmpty(scores)) {
System.err.println("参数错误!");
}
// Map<Integer, Long> map = scores.stream().collect(Collectors.groupingBy(e -> e, Collectors.counting()));
// System.err.println("集合:" + map); 取出所有key排序,然后遍历打印名次
// 倒序
// scores.sort(Comparator.reverseOrder());
scores.sort(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2 - o1;
}
});
int size = scores.size();
if (size == 1) {
System.err.println("数组仅有一个数: " + scores);
}
List<Integer> keys = new ArrayList<>();
Map<Integer, Integer> score2NumMap = new LinkedHashMap<>();
for (int i = 0; i < size; i++) {
Integer key = scores.get(i);
if (score2NumMap.containsKey(key)) {
score2NumMap.put(key, score2NumMap.get(key) + 1);
} else {
score2NumMap.put(key, 1);
keys.add(key);
}
}
System.err.println("*********分数相同,排名连续,不同名次************");
int ranking = 1;
for (int i = 0; i < score2NumMap.size(); i++) {
int score = keys.get(i);
int number = score2NumMap.get(score);
System.err.println("分数:" + score + ",排名:" + ranking);
// 按分数连续排名
if (number > 1) {
for (int j = 1; j < number; j++) {
++ranking;
System.err.println("分数:" + score + ",排名:" + ranking);
}
}
ranking = ranking + 1;
}
System.err.println("**********以下分数相同,排名相同,不连续排名************");
// 分数相同,排名相同
int rankingOther = 1;
for (int i = 0; i < score2NumMap.size(); i++) {
int score = keys.get(i);
int number = score2NumMap.get(score);
System.err.println("分数:" + score + ",排名:" + rankingOther);
// 按分数连续排名
if (number > 1) {
for (int j = 1; j < number; j++) {
System.err.println("分数:" + score + ",排名:" + rankingOther);
}
rankingOther = rankingOther + number;
}
rankingOther = rankingOther + 1;
}
System.err.println("**********以下分数相同,排名相同,连续排名************");
int rankingAnother = 1;
for (int i = 0; i < score2NumMap.size(); i++) {
int score = keys.get(i);
int number = score2NumMap.get(score);
System.err.println("分数:" + score + ",排名:" + rankingAnother);
// 按分数连续排名
if (number > 1) {
for (int j = 1; j < number; j++) {
System.err.println("分数:" + score + ",排名:" + rankingAnother);
}
}
rankingAnother = rankingAnother + 1;
}
}
}
排名算法实现