java如何从中读取字符串。txt文件,并根据出现的次数将其排序到ArrayList中?
我有一个程序可以读取。txt文件,创建一个包含每个唯一字符串及其出现次数的HashMap,我想创建一个ArrayList,根据这些唯一字符串的出现次数降序显示它们
目前,我的程序从字母顺序的角度按降序排序(我假设使用ASCII值)
我该如何根据它们出现的次数按降序排列
以下是代码的相关部分:
Scanner in = new Scanner(new File("C:/Users/ahz9187/Desktop/counter.txt"));
while(in.hasNext()){
String string = in.next();
//makes sure unique strings are not repeated - adds a new unit if new, updates the count if repeated
if(map.containsKey(string)){
Integer count = (Integer)map.get(string);
map.put(string, new Integer(count.intValue()+1));
} else{
map.put(string, new Integer(1));
}
}
System.out.println(map);
//places units of map into an arrayList which is then sorted
//Using ArrayList because length does not need to be designated - can take in the units of HashMap 'map' regardless of length
ArrayList arraylist = new ArrayList(map.keySet());
Collections.sort(arraylist); //this method sorts in ascending order
//Outputs the list in reverse alphabetical (or descending) order, case sensitive
for(int i = arraylist.size()-1; i >= 0; i--){
String key = (String)arraylist.get(i);
Integer count = (Integer)map.get(key);
System.out.println(key + " --> " + count);
}
# 1 楼答案
在Java 8中:
首先,使用
Files.lines
方法读取文件,该方法会给出Stream<String>
行现在,使用
Map.merge
方法将这些行收集到Map<String, Integer>
中,该方法接受一个键和一个值,以及一个lambda,如果键已经存在,该lambda将应用于旧值和新值你现在有你的计数了
现在从{}的{}中取一个{},然后按每个{}的{}排序,然后取{}。把它收集到
List
。现在,您有了按计数排序的List
个值现在只需使用
forEach
来打印它们如果仍然使用Java 7,则可以使用
Map
来提供排序顺序:# 2 楼答案
您还没有显示地图的声明,但为了回答这个问题,我假设您的地图声明如下:
您需要在调用排序时使用
Comparator
,但需要在记住字符串的同时按计数进行比较。所以你需要把对象放在既有字符串又有计数的列表中。 提供这种功能的一种类型是Map.entrySet
类型,这种类型很容易从Map.Entry
方法获得最后一部分用
Map.Entry
和Comparator
重写: