有谁知道如何使用内置的 collection.sort
和 comparator<string>
接口将单词列表按照频率(从小到大)排序吗?
我已经有一个函数可以获取文本文件中某个单词的计数了。现在,我需要创建一个方法来比较每个单词的计数,然后将它们放入按最小频率到最大频率排序的列表中。
非常感谢您提供任何想法和提示。我在开始这个特定的方法上遇到了麻烦。
public class Parser implements Comparator<String> {
public Map<String, Integer> wordCount;
void parse(String filename) throws IOException {
File file = new File(filename);
Scanner scanner = new Scanner(file);
//mapping of string -> integer (word -> frequency)
Map<String, Integer> wordCount = new HashMap<String, Integer>();
//iterates through each word in the text file
while(scanner.hasNext()) {
String word = scanner.next();
if (scanner.next()==null) {
wordCount.put(word, 1);
}
else {
wordCount.put(word, wordCount.get(word) + 1);;
}
}
scanner.next().replaceAll("[^A-Za-z0-9]"," ");
scanner.next().toLowerCase();
}
public int getCount(String word) {
return wordCount.get(word);
}
public int compare(String w1, String w2) {
return getCount(w1) - getCount(w2);
}
//this method should return a list of words in order of frequency from least to greatest
public List<String> getWordsInOrderOfFrequency() {
List<Integer> wordsByCount = new ArrayList<Integer>(wordCount.values());
//this part is unfinished.. the part i'm having trouble sorting the word frequencies
List<String> result = new ArrayList<String>();
}
}
Comparable<Yourclass>
接口,然后在compareTo(...)方法中,按照整数值进行比较。 - Hovercraft Full Of EelsCollections.sort(justTheWords, this)
。 - Torious//this part is unfinished
处,只需执行:List<String> justWords = new ArrayList<String>(wordCount.keySet()); List<String> result = Collections.sort(justWords, this);
... - Torioussort
会调用this.compare()
来比较两个String
,然后通过首先查找this
(即Parser
实例)中的计数来进行比较。这是假设先调用了parse
的情况下。我看compare
方法的意图就是这样。我有什么遗漏吗? - Torious