【问题标题】:Transform ConcurrentHashMap into a sorted list in Java将 ConcurrentHashMap 转换为 Java 中的排序列表
【发布时间】:2015-04-13 22:06:26
【问题描述】:

在Java8中,计算ConcurrentHashMap中的数据后,

// this is a working code, which I want to simplify
ConcurrentMap<String, AtomicInteger> data =
    new ConcurrentHashMap<String, AtomicInteger>();
// ... (fill in the data object)
final int l = data.keySet().size();
P[] points = new P[l];
int i = 0;
for (Map.Entry<String, AtomicInteger> entry : data.entrySet())
    points[i++] = new A(entry.getKey(), entry.getValue().get() * 1.0 / 105);
Arrays.sort(points);

我想实现这个:

data.parallelStream()
.map( (k, v) -> new A(k, v.get() * 1.0 / 105) )
.sort().forEach(System.out::println)

如何正确地做到这一点?

【问题讨论】:

  • 您可能应该检查在已经并发的 Map 实现中是否真的需要 AtomicInteger 作为值类型。

标签: java parallel-processing java-8 java-stream concurrenthashmap


【解决方案1】:

我想这就是你想要的。需要创建Entry对象的Stream,所以不能写(k, v)-&gt;

data.entrySet()
    .parallelStream()
    .map(e -> new A(e.getKey(), e.getValue().get() * 1.0 / 105))
    .sorted()
    .forEachOrdered(System.out::println);

【讨论】:

  • 当你的答案一开始是正确的以保持我的支持时,我会感觉很糟糕,所以我删除并支持你的答案。
  • @Jean-François Savard 你仍然是最棒的 :)
  • @StephanRozinsky 实际上我完全没有通过这个答案,即使我原来的答案也充满了其他人(感谢他)修复的错别字。
  • @Jean-FrançoisSavard 谢谢。我在您的原件还在的时候发布了这个版本,所以这不仅仅是抄袭。我发现其他人可以编辑您的答案很奇怪。如果有人编辑了我的答案,因此我得到了大量的赞成/反对票,我能做些什么吗?
  • @pbabcdefp 如果您认为编辑不好,那么您可以回滚它。否则,如果它很好,那么只需享受赞成票:)。
猜你喜欢
  • 2010-11-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-16
  • 2015-07-29
  • 2015-06-20
  • 1970-01-01
相关资源
最近更新 更多