我目前正在寫這將使用Hashtable
來計數文件中的單詞一個單詞計數程序,我想創建程序內的鏈接列表進行排序的話降序排列的發生。如何將元素添加到HashTable的LinkedList中並對它們進行排序?
我知道如何將元素添加到鏈接列表,但我不知道如何將元素從Hashtable
添加到鏈接列表並按降序對值進行排序。你能幫忙嗎?
這裏是我的代碼至今:
import java.io.FileReader;
import java.util.*;
import java.util.Hashtable;
import java.util.stream.Collectors;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
public class WordCounter {
public Hashtable count_words(String contents) {
Hashtable < String, Integer > count = new Hashtable < String, Integer >();
Set <String> key = count.keySet();
StringTokenizer w = new StringTokenizer(contents);
while (w.hasMoreTokens()) {
String word = w.nextToken();
word = word.toLowerCase();
word = word.replaceAll("[-+.^:(\"),']", "");
if (count.containsKey(word)) {
count.put(word, count.get(word) + 1);
} else {
count.put(word, 1);
}
}
return count;
}
public LinkedList top20(Hashtable count) {
///I don't know how to add elements from hashtable to linkedlist
return new LinkedList();
}
public static void main(String args[]) {
try {
String contents = "";
Scanner in = new Scanner(new FileReader("src/ADayInTheLife.txt"));
while (in .hasNextLine()) {
contents += in .nextLine() + "\n";
}
WordCounter wc = new WordCounter();
Hashtable count = wc.count_words(contents);
System.out.println(count);
} catch (Exception e) {
System.err.println("Error " + e.getMessage());
}
}
}
這將更有意義使用的'ArrayList',因爲你已經知道有多少它ems有,你可以用'Collections.sort()'來排序。 – EJP