我已經將文件中的字符串存儲到ArrayList中,並使用HashSet來計算每個字符串的出現次數。從文本文件中排序字符串出現
我在尋找列出前5個單詞及其出現次數。我應該能夠完成這個沒有實現哈希表,樹形圖等等。我該如何去實現這個?
這裏是我的ArrayList:
List<String> word_list = new ArrayList<String>();
while (INPUT_TEXT1.hasNext()) {
String input_word = INPUT_TEXT1.next();
word_list.add(input_word);
}
INPUT_TEXT1.close();
int word_list_length = word_list.size();
System.out.println("There are " + word_list_length + " words in the .txt file");
System.out.println("\n\n");
System.out.println("word_list's elements are: ");
for (int i = 0; i<word_list.size(); i++) {
System.out.print(word_list.get(i) + " ");
}
System.out.println("\n\n");
這裏是我的HashSet:
Set<String> unique_word = new HashSet<String>(word_list);
int number_of_unique = unique_word.size();
System.out.println("unique worlds are: ");
for (String e : unique_word) {
System.out.print(e + " ");
}
System.out.println("\n\n");
String [] word = new String[number_of_unique];
int [] freq = new int[number_of_unique];
int count = 0;
System.out.println("Frequency counts : ");
for (String e : unique_word) {
word[count] = e;
freq[count] = Collections.frequency(word_list, e);
System.out.println(word[count] + " : "+ freq[count] + " time(s)");
count++;
}
難道是我一個得太多一步?由於事先
創建一個內部類,說Z,具有兩個字段 - 字,它實現'可比'和覆蓋'哈希碼()'和'的equals計數() '方法。創建該類的實例集 - 如果設置包含對象獲取它並增加計數。使用'Collections.sort()'對其進行排序。你去了。 –
GurV
也就是說,Hashmap可能是更好的方法 – GurV
Apache Commons中有一個簡單的實現,使用'HashBag' – ifly6