ビルトイン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>();
}
}