HashMap 和列表

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


编辑


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


干杯


构建哈希图


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


蝴蝶刀刀
浏览 164回答 3
3回答

慕神8447489

根据定义,Java HashMap 未排序。它明确地写在Javadoc 中:此类不保证地图的顺序;特别是,它不保证订单会随着时间的推移保持不变。如果您想要按其键排序的 Map,请使用TreeMap:映射根据其键的自然顺序进行排序,或者通过映射创建时提供的 Comparator 进行排序,具体取决于使用的构造函数。但是,我不确定 Map 是否真的是您想要的。映射用于通过键查找值。排序映射对键进行排序,看起来您要对值进行排序(出现次数)。如果你有两个单词出现的次数相同,它们应该在什么键下出现呢?这就是为什么要Collections.sort()返回一个列表 - 它对给定的集合进行排序并按照您想要的顺序放置元素。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java