【发布时间】:2014-07-25 08:46:10
【问题描述】:
我有一个程序可以读取 .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);
}
【问题讨论】:
-
使用自定义
Comparator。从HashMap获取出现次数并比较... -
并使用 entrySet() 而不是 keySet(),所以你有唯一的字符串和出现的次数。
-
使用
Comparator将完成的 HashMap 中的所有项目推入PriorityQueue,就像 Boris 所说的那样。你想要的是一个最大堆,所以一旦你把所有东西都放入了 priqueue(按出现次数排序),你就可以poll()直到你提取所有元素。 -
旁注:
Integer支持+运算符:map.put(string, map.get(string) + 1);。 @BoristheSpider 你为什么不回答而不是评论? -
@sp00m 如果你坚持的话。
标签: java sorting arraylist hashmap counter