Home > Blockchain >  Create map using parallel stream
Create map using parallel stream

Time:10-09

I have this working code to create a map and populate using parallel stream

SortedMap<Double, Double> map = new TreeMap<>();

for (double i = 10d; i < 50d; i  = 2d)
    map.put(i, null);
    
map.entrySet().parallelStream().forEach(e -> {
    double res = bigfunction(e.getKey());
    e.setValue(100d - res); 
});

How can the above code be written efficiently

Incomplete code:

SortedMap<Double, Double> map = DoubleStream.iterate(10d, i -> i   2d).limit(20)
  .parallel().collect(Collectors.toConcurrentMap(k -> k, k -> {
    double res = bigfunction(k);
    return 100d - res;
}, null, TreeMap::new));
  • What should be the mergeFunction in this case
  • What changes are required to make this work

CodePudding user response:

A few things. First, you need to box the primitive DoubleStream by calling boxed() in order to use it with a Collector. Second, you don't need toConcurrentMap(). It's safe to call toMap() on a parallel stream. Finally, the merge function will never be invoked in this scenario, because you're iterating over distinct keys, so I would go with what's simplest:

SortedMap<Double, Double> map = DoubleStream.iterate(10d, i -> i   2d)
        .limit(20)
        .boxed()
        .parallel()
        .collect(Collectors.toMap(
                i -> i, i -> 100d - bigfunction(i), (a, b) -> b, TreeMap::new));
  • Related