-7

Could you please explain how does this code work ? I can not understand how this code works.

        HashMap<String, Integer> countMap = new HashMap<String, Integer>();
        for (String string : strArray) {
            if (!countMap.containsKey(string)) {
                countMap.put(string, 1);
            } else {
                Integer count = countMap.get(string);
                count = count + 1;
                countMap.put(string, count);
            }
        }
        printCount(countMap);
    }


    private static void printCount(HashMap<String, Integer> countMap) {
        Set<String> keySet = countMap.keySet();
        for (String string : keySet) {
            System.out.println(string + " : " + countMap.get(string));
        }
    }
}
  • https://www.geeksforgeeks.org/count-occurrences-elements-list-java/ should explain a bit more. Basic concept is to put the strings from array as keys in hashmap and then increment the count for earch occurence. If a particular string isn't in the hashmap, add the string as a key and put the count as 1, and keep incrementing the count from there on. – Amey Kulkarni Jan 23 '20 at 16:55
  • Thanks. Your link was very useful. What does that mean though : ? Integer j = count.get(i); count.put(i, (j == null) ? 1 : j + 1); – Krystian Małysek Jan 24 '20 at 08:52
  • Let me break it down for you: `Integer j = count.get(i);` gets the current count of i from the hashmap. `count.put(i,` part puts in the hashmap with i as a key. `(j == null) ? 1 : j + 1)` checks if the current count is null (meaning the item being added isn't in the map) initializes the count as 1 else gets the current count and increases by 1. Hope that makes sense. – Amey Kulkarni Jan 24 '20 at 17:40

1 Answers1

1

Initially, your hashmap does not contain any value

 HashMap<String, Integer> countMap = new HashMap<String, Integer>();

Now, you are running a loop on supposedly list of string, that is strArray.

  for (String string : strArray) {

Here you are checking if your map contains iterating key i.e. string

which it does not for the first iteration(or any key not in countmap), so it put string as key and 1 as value

  if (!countMap.containsKey(string)) {              
     countMap.put(string, 1);
        } else {

if countMap contains the string then you are fetching the value for the given key and in that value you are adding one and put it back in countmap (basically replacing the old value with incremented value)

            Integer count = countMap.get(string);
            count = count + 1;
            countMap.put(string, count);
        }

    }

Later, you are printing the key and its value.

   printCount(countMap);
}
Shubham
  • 549
  • 4
  • 11