将ConcurrentHashMap转换为Java中的排序列表

时间:2015-04-13 22:06:26

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

在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)

如何正确地做到这一点?

1 个答案:

答案 0 :(得分:4)

我认为这就是你想要的。您需要创建StreamEntry个对象,这样您就无法写(k, v)->

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