Map<Object, AtomicInteger> 到关联数组

Map<Object, AtomicInteger> to Associative array

我要输入 int[],内容如下:

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

使用 Map<Object, AtomicInteger>,我将其转换为以下对象:

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

换句话说,我正在计算动态数组的重复元素。

现在我需要找出出现次数的最大值和最小值,但我真的被困在进一步的步骤中了。

重复元素class的代码如下:

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;
}

如果要查找最大和最小出现次数,请使用 EntrySet 遍历 Map 并比较每个键的值。

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());