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;
}
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
}
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());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.