java - 使用原始数组在 Java 中创建排行榜

标签 java arrays sorting console leaderboard

<分区>

我正在用 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 - 使用原始数组在 Java 中创建排行榜,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53326613/

相关文章:

c++ - ifstream读入二维数组时出现奇怪的字符

perl - 奇怪的行为

java - 如何按项目类型按字母顺序对 java 链接(不是集合 LinkedList)列表进行排序?

java - 枚举常量中局部变量的范围

java - 如何将 Fragment 的上下文转换为界面

java - 比较字符串时忽略字体类型

java - 如何初始化 TIME 数组? java 语

python - 在 numpy 中 reshape ndarray 与常规数组?

python - 根据另一个列表中子字符串的顺序对列表进行排序

java - 使用 Camel 提取文件名中的值