【问题标题】:Map<Object, AtomicInteger> to Associative array将<Object, AtomicInteger> 映射到关联数组
【发布时间】:2020-07-23 08:24:12
【问题描述】:

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

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

使用Map&lt;Object, AtomicInteger&gt;,我将其转换为以下对象:

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

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

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

重复元素类的代码如下:

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

【问题讨论】:

  • 两侧cmets:1.我很好奇为什么Map&lt;Object, AtomicInteger&gt;而不是Map&lt;Integer, AtomicInteger&gt; 2.除非同时使用此方法的结果,否则您仍然可以使用HashMap&lt;Object, Integer&gt;(您可以使用output.compute来增加/增加)

标签: java java-8 mapping atomic atomicinteger


【解决方案1】:

如果你想找到最大值和最小值,使用 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
}

【讨论】:

  • min = entry.getValue();抛出应该是 AtomicInteger 类型的警告
  • 更新的代码,应该是 getValue().intValue() 因为您将 AtomicInteger 转换为 int。或者,您可以将 min 和 max 变量设置为 AtomicInteger 并相应地更改您的实现。
【解决方案2】:
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());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多