我目前正在写这将使用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