2016-09-13 64 views
3

我以Map<String,List<Rating>>开头。评级有一个方法int getValue()通过属性将地图列表值转换为平均值

我想最终与Map<String,Integer>其中整数值是从原始Map<String,List<Rating>>按键分组的所有Rating.getValue()值的平均值。

我很乐意收到一些关于如何解决这个问题的想法。

回答

4

使用IntStream方法可以对整数集合执行聚合操作。在你的情况下,average似乎是正确的使用方法(注意它返回Double,而不是Integer,这似乎是一个更好的选择)。

想要的是将原始映射的每个条目转换为新映射中的条目,其中键保持不变,并且该值是List<Rating>元素的值的平均值。生成输出映射可以使用toMapCollector完成。

Map<String,Double> means = 
    inputMap.entrySet() 
      .stream() 
      .collect(Collectors.toMap(Map.Entry::getKey, 
             e->e.getValue() 
              .stream() 
              .mapToInt(Rating::getValue) 
              .average() 
              .orElse(0.0))); 
+0

我觉得它不能实施得更好! –

+0

@Eran,你是对的,它实际上是我想要的Double。现在我将看看您的示例是否可以通过我现有的测试并回报。 – jdh961502

4

它可以通过averagingInt作为下一步要做:

Map<String, Double> means = 
    map.entrySet() 
     .stream() 
     .collect(
      Collectors.toMap(
       Map.Entry::getKey, 
       e -> e.getValue().stream().collect(
        Collectors.averagingInt(Rating::getValue) 
       ) 
      ) 
     ); 

假设你想走得更远一点,你需要更多的统计资料,例如countsumminmaxaverage,你可以考虑使用summarizingInt来代替,然后你会得到IntSummaryStatistics而不是Double

Map<String, IntSummaryStatistics> stats = 
    map.entrySet() 
     .stream() 
     .collect(
      Collectors.toMap(
       Map.Entry::getKey, 
       e -> e.getValue().stream().collect(
        Collectors.summarizingInt(Rating::getValue) 
       ) 
      ) 
     ); 
相关问题