Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - groupingBy with collectingAndThen - 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 by AlgorithmPrediction objects with the algorithmName (unique) as key and productsToAccuracy as value. I couldn't come up with anything less complex than this:

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

This can't be right. What am I missing? Thank you!

like image 951
Julian Pieles Avatar asked Aug 26 '15 08:08

Julian Pieles


2 Answers

algorithmPredictions.stream()
                    .collect(toMap(AlgorithmPrediction::getAlgorithmName, 
                                   AlgorithmPrediction::getProductsToAccuracy));
like image 97
JB Nizet Avatar answered Sep 20 '22 02:09

JB Nizet


If I've understood you correctly, couldn't you use Collectors.toMap(Function<> keyMapper, Function<> valueMapper) collector, like the following:

Map<String, Map<BaseDatabaseProduct, Double>> result = algorithmPredictions.stream()
        .collect(Collectors.toMap(
                AlgorithmPrediction::getAlgorithmName,
                AlgorithmPrediction::getProductsToAccuracy));
like image 35
Edd Avatar answered Sep 22 '22 02:09

Edd