使用一个有序的集合,就像TreeMap
它保持其条目(键值映射)在其键的自然顺序中一样。因为,您想对高分进行排序,将您的分数作为键,将玩家作为他们的值。
两个或更多玩家很可能获得相同的高分。因此,我们不必将分数映射到一个玩家,而是将它映射到一个List
玩家(具有相同的高分):
// {key - value} = {high score - {list, of, players}}
TreeMap<Integer, List<Client>> highestScores =
new TreeMap<Integer, List<Client>>();
for (Client client : getPlayers()) {
List<Client> playerList = null;
// make gameScore private
Integer score = client.getGameScore(); // using getters() recommended
// check if a player with this score already exists
if ((playerList = highestScores.get(score)) == null) { // if NOT,
playerList = new ArrayList<Client>(1); // CREATE a new list
playerList.add(client);
highestScores.put(score, playerList);
} else { // if YES, ADD to the existing list
playerList.add(client);
}
}
遍历所有高分使用
for (Integer score : highestScores.descendingKeySet()) {
for (Client player : highestScores.get(score)) { // iterate over player list
System.out.println(player.getName() + ": " + score); // assuming "name" property
}
}
直接打印出最高分使用
Map.Entry<Integer, List<Client>> highest = highestScores.lastEntry();
System.out.println(highest.getKey() + " : " + highest.getValue());