java - 使用原始数组在 Java 中创建排行榜
问题描述
我正在用 Java 创建一个控制台游戏。我想跟踪分数和名字。
我已经创建了两个数组。
String[] PlayerNames = {"Bob", "Rick", "Jack"}; // just an example
int[] PlayerScores = {40, 20, 60}; // just an example
我想对他们的分数进行排序,还要知道分数属于谁,然后打印出来是这样的:
Jack 60
Bob 40
Rick 20
解决方案
创建一个map
以玩家姓名为键,分数为值,然后map
根据值排序:
public static void main(String[] args) {
Map<String, Integer> unsortedMap = new HashMap<String, Integer>();
unsortedMap.put("Jack", 60);
unsortedMap.put("Bob", 40);
unsortedMap.put("Rick", 20);
Map<String, Integer> sortedMap = sortByValue(unsortedMap);
printMap(sortedMap);
}
private static Map<String, Integer> sortByValue(Map<String, Integer> unsortMap) {
// 1. Convert Map to List of Map
List<Map.Entry<String, Integer>> list =
new LinkedList<Map.Entry<String, Integer>>(unsortMap.entrySet());
// 2. Sort list with Collections.sort(), provide a custom Comparator
// Try switch the o1 o2 position for a different order
Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
public int compare(Map.Entry<String, Integer> o1,
Map.Entry<String, Integer> o2) {
return (o1.getValue()).compareTo(o2.getValue());
}
});
// 3. Loop the sorted list and put it into a new insertion order Map LinkedHashMap
Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
for (Map.Entry<String, Integer> entry : list) {
sortedMap.put(entry.getKey(), entry.getValue());
}
/*
//classic iterator example
for (Iterator<Map.Entry<String, Integer>> it = list.iterator(); it.hasNext(); ) {
Map.Entry<String, Integer> entry = it.next();
sortedMap.put(entry.getKey(), entry.getValue());
}*/
return sortedMap;
}
public static <K, V> void printMap(Map<K, V> map) {
for (Map.Entry<K, V> entry : map.entrySet()) {
System.out.println("Key : " + entry.getKey()
+ " Value : " + entry.getValue());
}
}
注意:有关详细信息,请参阅https://www.mkyong.com/java/how-to-sort-a-map-in-java/ 。
推荐阅读
- java - Spring Integration 在下一个之前完成异步转换
- hyperledger-fabric - 阅读 Hyperledger Fabric 中的旧交易
- c# - 使用 Azure 存储模拟器的 HTTPS 重定向
- r - R中的头/尾中断分类算法
- azure - 在 Azure 认知服务上托管的自定义视觉模型的推理在 12 月停止了对我的工作
- html - 子资源完整性和 Nonce 值
- python - 寻找矩形的角
- scala - 空安全“之间” Spark 运算符
- rest - Acumatica REST API - 如何在检索 Stockitem 时包含扩展数据
- python - 用于循环的打印字符串中的索引的Python错误