使用像TreeMap这样的有序集合,它按照键的自然顺序保存其条目(键值映射)。因为,您希望对高分进行排序,将分数作为键和玩家名称作为其值。
// instantiate your sorted collection
Map highestScores = new TreeMap();
// setup a file reader
BufferedReader reader = new BufferedReader(
new FileReader(new File("/path/to/file")));
String line = null;
while ((line = reader.readLine()) != null) { // read your file line by line
String[] playerScores = line.split(": ");
// populate your collection with score-player mappings
highestScores.put(Integer.valueOf(playerScores[1]), playerScores[0]);
}
// iterate in descending order
for (Integer score : highestScores.descendingKeySet()) {
System.out.println(highestScores.get(score) + ": " + score);
}
的输出强>的
Eric: 25
Oscar: 18
Bert: 16
John: 12
Carl: 9
修改强>
两个或更多玩家很可能拥有相同的高分。因此,排序后的集合必须更加复杂,但如果您已经理解了上面的那个,那么理解这个集合就不会有麻烦了。
现在我们不得不将得分映射到玩家,我们必须将其映射到List个玩家(具有相同的高分):
// {key - value} = {high score - {list, of, players}}
TreeMap> highestScores =
new TreeMap>();
BufferedReader reader = new BufferedReader(
new FileReader(new File("/path/to/file")));
String line = null;
while ((line = reader.readLine()) != null) {
String[] playerScores = line.split(": ");
Integer score = Integer.valueOf(playerScores[1]);
List playerList = null;
// check if a player with this score already exists
if ((playerList = highestScores.get(score)) == null) { // if NOT,
playerList = new ArrayList(1); // CREATE a new list
playerList.add(playerScores[0]);
highestScores.put(Integer.valueOf(playerScores[1]), playerList);
} else { // if YES, ADD to the existing list
playerList.add(playerScores[0]);
}
}
// iterate in descending order
for (Integer score : highestScores.descendingKeySet()) {
for (String player : highestScores.get(score)) { // iterate over player list
System.out.println(player + ": " + score);
}
}
的输出强>的
Eric: 25
Oscar: 18
Bert: 16
John: 12 *
Jane: 12 *
Carl: 9