Java - groupingBy with collectAndThen - is there a faster / better / cleaner way?

I have the following class (with getters):

public class AlgorithmPrediction { private final String algorithmName; private final Map<BaseDatabaseProduct, Double> productsToAccuracy; } 

Now I want to create a map from a set filled with AlgorithmPrediction objects, with the algorithmName key (unique) and productsToAccuracy as the value. I could not come up with anything more complicated than this:

 algorithmPredictions.stream() .collect( groupingBy( AlgorithmPrediction::getAlgorithmName, Collectors.collectingAndThen( toSet(), s -> s.stream().map(AlgorithmPrediction::getProductsToAccuracy).collect(toSet()) ) ) ); 

It is not right. What am I missing? Thanks!

+6
source share
2 answers
 algorithmPredictions.stream() .collect(toMap(AlgorithmPrediction::getAlgorithmName, AlgorithmPrediction::getProductsToAccuracy)); 
+6
source

If you understood correctly, could you please use Collectors.toMap(Function<> keyMapper, Function<> valueMapper) collector, as shown below:

 Map<String, Map<BaseDatabaseProduct, Double>> result = algorithmPredictions.stream() .collect(Collectors.toMap( AlgorithmPrediction::getAlgorithmName, AlgorithmPrediction::getProductsToAccuracy)); 
+4
source

All Articles