我制作了一个函数,可以读取文本文件,并通过使用哈希图来计算单词的出现频率。然后,我发现制作一个对哈希图进行排序的函数非常困难...因此,经过一些研究,我发现了一些使用集合和列表对哈希图进行排序的代码。但是,此函数的输出是列表,而不是哈希图。一切正常,并且完全符合我的要求。所以我的问题是,获取列表内容并将其放回哈希表的最有效方法是什么,以便它可与我的其余代码一起使用。

编辑

好的,所以我很清楚这无法实现,因为它不是使用哈希图时的目的。我问这的唯一原因是因为我有现有代码(在必须执行更改之前)将其输出到文件中。这在使用哈希表时有效,但是现在我有点困惑了。

干杯

建立哈希图

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()

最佳答案

Java HashMaps根据定义未排序。它明确地写在Javadoc中:


  此类无法保证地图的顺序。在
  特别是,它不能保证订单将保持不变
  随着时间的推移。


如果要按其键对地图排序,请使用TreeMap


  该地图是根据其键的自然顺序或通过
  地图创建时提供的比较器,具体取决于哪个
  使用构造函数。


但是,我不确定地图是否真的是您想要的。映射用于通过键查找值。排序的映射对键进行排序,看起来您想对值(出现的次数)进行排序。如果您有两个单词出现相同的次数,应该在哪个键下出现呢?

这就是Collections.sort()返回列表的原因-它对给定的集合进行排序,并将元素按所需的顺序放置。

09-10 03:01
查看更多