Stephan Rozinsky
Stephan Rozinsky

Reputation: 623

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?

Upvotes: 1

Views: 1114

Answers (1)

Paul Boddington
Paul Boddington

Reputation: 37645

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

Upvotes: 4

Related Questions