Counting occurrences of a key in a Map in Java

后端 未结 5 1765
别那么骄傲
别那么骄傲 2020-12-17 02:37

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

5条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-17 03:25

    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.

    The inner part should be something like:

            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.

提交回复
热议问题