Counting occurrences of a key in a Map in Java

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

    Even more concise using Map.merge() (since Java 8):

    if (keywordSet.contains(key)) {
        map.merge(key, 1, (currentCount, notUsed) -> ++currentCount);
    }
    

    Here is a generic implementation of a counting map - a map with values representing the count of their keys:

    public static  void count(K key, Map map) {
        map.merge(key, 1, (currentCount, notUsed) -> ++currentCount);
    }
    
    public static void main(String[] args) {
        Map map = new HashMap<>();
        count("A", map);
        count("B", map);
        count("A", map);
        count("Z", map);
        count("A", map);
        System.out.println(map); // {A=3, B=1, Z=1}
    }
    

提交回复
热议问题