【问题标题】:Java - groupingBy with collectingAndThen - Is there a faster / better / cleaner way?Java - groupingBy 和 collectAndThen - 有没有更快/更好/更清洁的方法?
【发布时间】:2015-08-26 08:51:38
【问题描述】:

我有以下课程(带有吸气剂):

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

现在我想从由AlgorithmPrediction 对象填充的集合中创建一个映射,其中algorithmName (unique) 作为键,productsToAccuracy 作为值。我想不出比这更复杂的东西了:

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

这不可能。我错过了什么?谢谢!

【问题讨论】:

标签: java lambda java-8 grouping collectors


【解决方案1】:
algorithmPredictions.stream()
                    .collect(toMap(AlgorithmPrediction::getAlgorithmName, 
                                   AlgorithmPrediction::getProductsToAccuracy));

【讨论】:

  • 谢谢。瞎了眼没看到。
【解决方案2】:

如果我的理解正确,你不能使用Collectors.toMap(Function&lt;&gt; keyMapper, Function&lt;&gt; valueMapper)collector,如下所示:

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

【讨论】:

  • @JulianLiebl 不用担心 :-) 很高兴你被排序了!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-01-16
  • 1970-01-01
  • 1970-01-01
  • 2012-07-08
  • 2013-10-17
  • 1970-01-01
  • 2019-01-10
相关资源
最近更新 更多