Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create map using parallel stream

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading