java 处理同分数排序例如 输入10010090输出:113使用stream流处理
使用Java的Stream流可以很方便地对分数进行排序处理。以下是一个示例代码:
import java.util.Arrays;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
int[] scores = {100, 100, 90};
Map<Integer, Long> sortedScores = Arrays.stream(scores)
.boxed()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet()
.stream()
.sorted((e1, e2) -> e2.getKey().compareTo(e1.getKey()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (v1, v2) -> v1, LinkedHashMap::new));
int[] ranks = Arrays.stream(scores)
.mapToObj(score -> sortedScores.get(score).intValue())
.mapToInt(Integer::intValue)
.toArray();
System.out.println(Arrays.toString(ranks));
}
}
输出结果为:[1, 1, 2]
首先,我们将分数数组转换为Stream流,然后使用Collectors.groupingBy方法按照分数进行分组统计,得到一个Map,其中Key为分数,Value为该分数的个数。
接着,我们使用entrySet方法将Map转换为Stream流,并通过sorted方法按照分数降序排序。
最后,我们使用Collectors.toMap方法将排序后的Map再次转换为Map,然后使用mapToObj方法将分数转换为对应的排名,最后使用mapToInt方法转换为int数组。
注意:为了确保排序后的Map保持插入顺序,我们使用了LinkedHashMap作为最终的Map实现类。
原文地址: https://www.cveoy.top/t/topic/jb7z 著作权归作者所有。请勿转载和采集!