2016-09-13 63 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) 
       ) 
      ) 
     ); 
相關問題