2

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;
}
Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
  • 1
    Two side comments: 1. I'm curious why `Map` instead of `Map` 2. unless this method's results are being used concurrently, you would still be fine with a `HashMap` (you can use `output.compute` to add/increment) – ernest_k Apr 10 '20 at 14:53

2 Answers2

2

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
}
Sidak
  • 1,213
  • 6
  • 11
  • min = entry.getValue(); throws warning that should be AtomicInteger type – Steven Clay Apr 10 '20 at 15:38
  • Updated code, Should be getValue().intValue() because you're converting an AtomicInteger to int. Alternatively, you can set the min and max variables to AtomicInteger and change your implementation accordingly. – Sidak Apr 10 '20 at 15:45
1
int[] inputArray = {5, 65, 22, 1, 58, 5, 69, 12, 1, 22, 22, 58, 12, 54, 89};

// 1
Map<Integer, Long> grouped = Arrays.stream(inputArray)
        .boxed()
        .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

// 2
LongSummaryStatistics stats = grouped.values()
        .stream()
        .mapToLong(Long::longValue)
        .summaryStatistics();

System.out.println(stats.getMax());
System.out.println(stats.getMin());
Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142