在 Java 中计算 Map 中键的出现次数 [英] Counting occurrences of a key in a Map in Java

查看:30
本文介绍了在 Java 中计算 Map 中键的出现次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个项目,该项目从 .java 文件中捕获 Java 关键字并使用地图跟踪出现的情况.我过去曾成功使用过类似的方法,但我似乎无法将这种方法用于我的预期用途.

I'm writing a project that captures Java keywords from a .java file and keeps track of the occurrences with a map. I've used a similar method in the past successfully, but I can't seem to adopt this method for my intended use here.

    Map<String,Integer> map = new TreeMap<String,Integer>();
    Set<String> keywordSet = new HashSet<String>(Arrays.asList(keywords));
    Scanner input = new Scanner(file);
    int counter = 0;
    while (input.hasNext())
    {
        String key = input.next();
        if (key.length() > 0)
        {
            if (keywordSet.contains(key))
            {
                map.put(key, 1);
                counter++;
            }

                if(map.containsKey(key)) <--tried inner loop here, failed
                {
                    int value = map.get(key);
                    value++;
                    map.put(key, value);
                }

        }

该代码块应该将关键字添加到键中,并在每次出现相同键时递增值.到目前为止,它添加了关键字,但未能正确增加值.这是一个示例输出:

This block of code is supposed to add the keyword to the key, and increment the value each time the same key occurs. So far, it adds the keywords, but fails to properly increment the value. here is a sample output:

{assert=2, class=2, continue=2, default=2, else=2, ...} 

基本上,它会增加地图中的每个值,而不是它应该增加的值.我不确定我是在想这个还是什么.我尝试了一个内部循环,它给了我疯狂的结果.我真的希望我只是想多了.非常感谢任何帮助!

Basically it increments every value in the map instead of the ones it's supposed to. I'm not sure if I'm over-thinking this or what. I've tried an inner loop and it gave me insane results. I really hope I'm just over-thinking this. Any help is greatly appreciated!

推荐答案

对于您扫描的每个键,您都会在映射中创建一个新条目(覆盖现有条目).然后,下一个条件成立,因此您将计数加 1,达到值 2.

For every key you scan you create a new entry in the map (overriding the existing one). Then, the next condition holds so you increment the count by 1, reaching the value 2.

内部应该是这样的:

        if (keywordSet.contains(key))
        {
            Integer value = map.get(key);
            if (value == null)
                value = 0;
            value++;
            map.put(key, value);
        }

无论如何,请考虑使用某种可变整数来提高效率.您不必覆盖地图中的条目,也不会执行过多的整数装箱操作.

Anyway, consider using some kind of a mutable integer to make this more efficient. You won't have to override entries in the map, and you won't be doing too much Integer boxing operations.

这篇关于在 Java 中计算 Map 中键的出现次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆