Wednesday 14 February 2024

HashMap's Merge function

Recently while working on a task i had to get count of each elements in an array. I follwed the way i have always did like :



Step 1 : Create one HashMap object called elementCountMap with elements of inputArray as keys and their occurrences as values.

Step 2 : Check every element of inputArray for its presence in elementCountMap.

Step 3 : If an element is already present in elementCountMap, increment it’s count by 1.


example :

 void arrayElementCount(int inputArray[])
    {
  
         
        HashMap<Integer, Integer> elementCountMap = new HashMap<Integer, Integer>();
         
         
        for (int i : inputArray)
        {
            if(elementCountMap.containsKey(i))
            {
               
                elementCountMap.put(i, elementCountMap.get(i)+1);
            }
            else
            {
                elementCountMap.put(i, 1);
            }
        }
         
         
    }
     

After my implementaion my IDE made a suggestion to make use of hashmap's merge method.
since i was not aware of how exactly it works i went ahead and did some java doc reading and see what, we have a well implememnted method for doing such sum, concatination etc opertaions on array of data when we want to convert it to create a counter map of data -> count.

here is the javadoc of merge method for your reference :

If the specified key is not already associated with a value or is associated with null, associates it with the given non-null value. Otherwise, replaces the associated value with the results of the given remapping function, or removes if the result is null. This method may be of use when combining multiple mapped values for a key. For example, to either create or append a String msg to a value mapping:
 map.merge(key, msg, String::concat)
If the remapping function returns null, the mapping is removed. If the remapping function itself throws an (unchecked) exception, the exception is rethrown, and the current mapping is left unchanged.
The remapping function should not modify this map during computation.
This method will, on a best-effort basis, throw a ConcurrentModificationException if it is detected that the remapping function modifies this map during computation.
Throws:
ConcurrentModificationException – if it is detected that the remapping function modified this map 


Same method as above with merge method :


void arrayElementCount(int inputArray[])
    {
         
        HashMap<Integer, Integer> elementCountMap = new HashMap<Integer, Integer>();
         
         
        for (int i : inputArray)
        {
          elementCountMap.merge(i, 1, Integer::sum);
        }
         
         
    }