2017-04-23 77 views
2

我有一個HashMap Map<String,List<Double>> incomeListString鍵和Double作爲值List,抱着這樣的數據:
如何使用Streams獲取列表圖的值的平均值?

seattle [50000.0 40000.0 30000.0] 
sanFrancisco [60000.0 100000.0] 

我想存儲的城市,在新HashMap其平均收入,這樣最後的結果是這樣的:

seattle 40000.0 
sanFrancisco 80000.0 

我使用這個代碼來創建此地圖:

Map<String,Double> avarage = incomeList.entrySet().stream() 
     .map(e -> e.getValue().stream().mapToDouble(Double::doubleValue).average()) 
     .collect(Collectors.toMap(Entry::getKey, Entry::getValue)); 

,但我收到此錯誤:

非靜態方法不能從靜態上下文中引用

有沒有人有一個線索,我怎麼能得到這個使用Stream s到工作?

+1

是什麼後的數據流保留的'map'?不是'Entry'實例,因此'Entry :: getKey'和'Entry :: getValue'不起作用。 – luk2302

回答

3

你應該收集到輸出Map當原始值(List<Double>)映射到平均:

Map<String,Double> avarage = 
    incomeList.entrySet() 
       .stream() 
       .collect(Collectors.toMap(Map.Entry::getKey, 
             e-> e.getValue() 
              .stream() 
              .mapToDouble(Double::doubleValue) 
              .average() 
              .getAsDouble()));