Reputation: 4016
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!
Upvotes: 8
Views: 7628
Reputation: 691725
algorithmPredictions.stream()
.collect(toMap(AlgorithmPrediction::getAlgorithmName,
AlgorithmPrediction::getProductsToAccuracy));
Upvotes: 8
Reputation: 3822
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));
Upvotes: 5