Counting occurrences of a key in a Map in Java

后端 未结 5 1755
别那么骄傲
别那么骄傲 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:23

    You always set the value to 1 and then update it by another one. What you need is to update the map value (and not setting it to 1 again).

    Instead of:

    map.put(key, 1);
    

    use:

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

    And drop the second if.

提交回复
热议问题