使用基本数组在Java中创建排行榜

时间:2018-11-15 19:24:57

标签: 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

2 个答案:

答案 0 :(得分:1)

创建一个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/

答案 1 :(得分:0)

您可以为此使用哈希图。使用playerNames中的每个名称作为键并创建值列表(以防两个或两个以上具有相同名称的玩家获得分数)。哈希图每个键只允许一个值,这就是为什么您应该为得分创建一个整数列表的原因。

Map<String, List<Integer>> scoreboard = new HashMap<>();