Java:通过HashMap获得文本中的500个最常用的词
||
我将单词计数存储到HashMap的value字段中,然后如何获取文本中的500个热门单词?
public ArrayList<String> topWords (int numberOfWordsToFind, ArrayList<String> theText) {
//ArrayList<String> frequentWords = new ArrayList<String>();
ArrayList<String> topWordsArray= new ArrayList<String>();
HashMap<String,Integer> frequentWords = new HashMap<String,Integer>();
int wordCounter=0;
for (int i=0; i<theText.size();i++){
if(frequentWords.containsKey(theText.get(i))){
//find value and increment
wordCounter=frequentWords.get(theText.get(i));
wordCounter++;
frequentWords.put(theText.get(i),wordCounter);
}
else {
//new word
frequentWords.put(theText.get(i),1);
}
}
for (int i=0; i<theText.size();i++){
if (frequentWords.containsKey(theText.get(i))){
// what to write here?
frequentWords.get(theText.get(i));
}
}
return topWordsArray;
}
没有找到相关结果
已邀请:
3 个回复
际恃啸称桅
。但是,更简单的是,您可以放弃循环:
现在您有了一个Multiset,该怎么办?好吧,您可以调用
,它为您提供了
对象的集合。然后,您可以将它们放在
中(它们放在
中),然后使用
对其进行分类。完整的代码可能看起来像(使用其他一些流行的Guava功能进行展示):
完成了!
荆怖赡
咳累录酬