我制作了一个函数,它读取文本文件并使用哈希图计算单词的频率。然后我发现制作一个对哈希图进行排序的函数很困难......所以经过一些研究,我发现了一些使用集合和列表对哈希图进行排序的代码。然而,这个函数的输出是一个列表,而不是一个哈希图。一切正常,并且完全符合我的要求。所以我的问题是,获取列表内容并将其放回哈希映射的最有效和最有效的方法是什么,以便它可以与我的其余代码一起使用。
编辑
好的,所以我很清楚这无法实现,因为它不是使用哈希图的目的。我问这个的唯一原因是因为我有将它输出到文件的现有代码(在我必须实施更改之前)。这在使用哈希图时有效,但现在它是一个列表,我有点困惑。
干杯
构建哈希图
private static HashMap<String, Integer> theHashMap(String inFileName) throws IOException {
// Resets collections frequency values to zero
for (Map.Entry<String, Integer> entry : collection.entrySet()) {
entry.setValue(0);
}
// Reads in the new document file to an ArrayList
Scanner textFile = new Scanner(new File(inFileName));
ArrayList<String> file = new ArrayList<String>();
while(textFile.hasNext()) {
file.add(textFile.next().trim().toLowerCase());
}
for(String word : file) {
Integer dict = collection.get(word);
if (!collection.containsKey(word)) {
collection.put(word, 1);
} else {
collection.put(word, dict + 1);
}
}
textFile.close();
return collection;
}
对哈希图进行排序
private static List<Map.Entry<String, Integer>> sortTheHashMap(HashMap<String, Integer> values) {
Set<Entry<String, Integer>> set = values.entrySet();
List<Entry<String, Integer>> list = new ArrayList<Entry<String, Integer>>(set);
Collections.sort( list, new Comparator<Map.Entry<String, Integer>>()
{
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2)
{
return (o2.getValue()).compareTo(o1.getValue());
}
} );
for(Map.Entry<String, Integer> entry:list){
System.out.println(entry.getKey()+" = "+entry.getValue());
}
return list;
}
输出到文件
FileWriter fw;
File fileName;
fileName = new File("test.txt");
fw = new FileWriter(fileName, true);
for (String word : document.getKey()) {
String key = word.toString();
String value = document.get(word);
fw.write(key + " " + value + "\n\n");
}
fw.close()
慕神8447489
相关分类