Search code examples
javaparallel-processingjava-8java-streamconcurrenthashmap

Transform ConcurrentHashMap into a sorted list in Java


In Java8, after computing the data in 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);

I want to achieve this:

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

How to do that properly?


Solution

  • I think this is what you want. You need to create a Stream of Entry objects, so you can't write (k, v)->.

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