Java - groupingBy 和 collectingAndThen - 有更快/更好/更清洁的方法吗?
Java - groupingBy with collectingAndThen - Is there a faster / better / cleaner way?
我有以下 class(带吸气剂):
public class AlgorithmPrediction {
private final String algorithmName;
private final Map<BaseDatabaseProduct, Double> productsToAccuracy;
}
现在我想从一个由 AlgorithmPrediction
个对象填充的集合创建一个地图,其中 algorithmName
(唯一) 作为键和 productsToAccuracy
作为价值。我想不出比这更简单的事情了:
algorithmPredictions.stream()
.collect(
groupingBy(
AlgorithmPrediction::getAlgorithmName,
Collectors.collectingAndThen(
toSet(),
s -> s.stream().map(AlgorithmPrediction::getProductsToAccuracy).collect(toSet())
)
)
);
这不对。我错过了什么?谢谢!
algorithmPredictions.stream()
.collect(toMap(AlgorithmPrediction::getAlgorithmName,
AlgorithmPrediction::getProductsToAccuracy));
如果我没理解错的话,你不能使用 Collectors.toMap(Function<> keyMapper, Function<> valueMapper)
收集器,如下所示:
Map<String, Map<BaseDatabaseProduct, Double>> result = algorithmPredictions.stream()
.collect(Collectors.toMap(
AlgorithmPrediction::getAlgorithmName,
AlgorithmPrediction::getProductsToAccuracy));
我有以下 class(带吸气剂):
public class AlgorithmPrediction {
private final String algorithmName;
private final Map<BaseDatabaseProduct, Double> productsToAccuracy;
}
现在我想从一个由 AlgorithmPrediction
个对象填充的集合创建一个地图,其中 algorithmName
(唯一) 作为键和 productsToAccuracy
作为价值。我想不出比这更简单的事情了:
algorithmPredictions.stream()
.collect(
groupingBy(
AlgorithmPrediction::getAlgorithmName,
Collectors.collectingAndThen(
toSet(),
s -> s.stream().map(AlgorithmPrediction::getProductsToAccuracy).collect(toSet())
)
)
);
这不对。我错过了什么?谢谢!
algorithmPredictions.stream()
.collect(toMap(AlgorithmPrediction::getAlgorithmName,
AlgorithmPrediction::getProductsToAccuracy));
如果我没理解错的话,你不能使用 Collectors.toMap(Function<> keyMapper, Function<> valueMapper)
收集器,如下所示:
Map<String, Map<BaseDatabaseProduct, Double>> result = algorithmPredictions.stream()
.collect(Collectors.toMap(
AlgorithmPrediction::getAlgorithmName,
AlgorithmPrediction::getProductsToAccuracy));