使用字符串和整数对文本文件进行排序 [英] Sort a text file with a String and Integer

查看:31
本文介绍了使用字符串和整数对文本文件进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,目前我正在研究一个项目,以帮助我练习Java.我有一个遵循教程的游戏,并且对其进行了一些修改,现在我试图找出一种对文本文件进行排序的方法,该文本文件先后带有String和Integer.我以前的尝试都以失败告终,但我还没有找到一个有效的在线资源.我已经成功地使用字符串按字母顺序对它进行了排序,但是我想按Integer值对其进行排序.

So currently I'm working on a project to just help me practice java. I have a game that I followed a tutorial on and I've modified it a bit, now I'm trying to figure out a way to sort a text file with a String followed by an Integer. My previous attempts have all failed and I have yet to find an online resource that has actually worked. I've successfully sorted it alphabetically using the String but I want to sort it by the Integer value.

文本文件示例

abc 31
adc 100
ccd 211
ddc 99

第一列将包含名称,第二列是玩家在我的游戏中获得的分数.

The first column will hold the name and the second column is the score the player got in my game.

我希望对它进行排序,使其顶部具有最高的得分"或整数"值,稍后将用于显示HighScore排行榜.

I am looking to have it sorted with the highest "score" or Integer value at the top, which will be later used to show a HighScore leaderboard.

示例排序

ccd 211
adc 100
ddc 99
abc 31

我尝试将信息添加到arrayList并使用collection.sort(),还尝试了更深入的路线,以通过将各行信息添加并添加到地图中来创建地图,从而帮助我更多地了解地图的工作方式.链接到entrySet()的链表,然后使用collections.sort(list,new比较器()),这是我认为我的逻辑在某些时候失败或我知道的事实在地图上变化不大的地方.

I've attempted adding the information to an arrayList and using collection.sort(), also I tried a more in depth route to help me understand more how maps work by creating and adding each lines information into a map, creating a linked list with entrySet(), then using a collections.sort(list, new comparator()) this is where I believe my logic failed at some point or the fact I know vary little on maps.

我们非常感谢您的帮助.

Any help is really appreciated.

推荐答案

正如您所说,您已经使用String成功地对其进行了排序.因此,您知道如何访问文件并将其存储在数据结构中.因此,现在让我们专注于基于Integer的排序.让我们考虑一下String和Integer存储在key_value HashMap中.

As you said, you have successfully sorted it using String. So you know how to access the file and store it in Data Structures. So now lets concentrate on sorting based on Integer. Let us consider that String and Integer is stored in key_value HashMap.

HashMap<String, Integer> key_value = new HashMap<String, Integer>();

现在让我们按降序对其进行排序:

Now lets Sort it in Descending Order:

String display = "";
List<Map.Entry<String, Integer>> list =
    new LinkedList<Map.Entry<String, Integer>>(key_value.entrySet());
Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
  public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
    return (o2.getValue()).compareTo(o1.getValue());
  }
});
for (Map.Entry<String, Integer> temp : list) {
  display += "\n " + temp.getKey() + " : " + temp.getValue();
}

对于升序,只需更改:

return (o2.getValue()).compareTo(o1.getValue());

return (o1.getValue()).compareTo(o2.getValue());

这篇关于使用字符串和整数对文本文件进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆