java 文本排序_如何使用Java按最高编号对文本文件进行排序

使用像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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值