javajava-8mappingatomicatomicinteger

Map<Object, AtomicInteger> to Associative array


I have for input int[] with the following content:

[5, 65, 22, 1, 58, 5, 69, 12, 1, 22, 22, 58, 12, 54, 89]

Using Map<Object, AtomicInteger>, I'm converting it to the following object:

{1=2, 65=1, 5=2, 69=1, 22=3, 58=2, 12=1}

In other words, I'm calculating the repeating elements of the dynamic array.

Now I need to find out the max and min occurrence and I'm really stuck on further steps.

The code of repeating elements class is below:

public Map<Object, AtomicInteger> countRepeatingElements(int[] inputArray) {
    ConcurrentMap<Object, AtomicInteger> output = 
                  new ConcurrentHashMap<Object, AtomicInteger>();

    for (Object i : inputArray) {
        output.putIfAbsent(i, new AtomicInteger(0));
        output.get(i).incrementAndGet();
    }

    return output;
}

Solution

  • If you want to find the max and the min occurrence, iterate through the Map using the EntrySet and compare the values of each key.

    int min = Integer.MAX_VALUE;
    int max = Integer.MIN_VALUE;
    for(Map.Entry<Object, AtomicInteger> entry : output.entrySet()){
        if(entry.getValue().intValue() < min){
            min = entry.getValue().intValue();
        }
        if(entry.getValue().intValue() > max){
            max = entry.getValue().intValue();
        }
    // entry.getValue() gives you number of times number occurs
    // entry.getKey() gives you the number itself
    }