从Java

时间:2018-09-08 20:16:00

标签: java java-8 java-stream collectors

我是Java 8的新手,我正在尝试以下方案。

class Numbers{
   private Long userId;
   private Long number1;
   private Long number2;

}

List<Numbers> list = new ArrayList();

Input == {
   "userId":1,
   "number1":10,
   "number2":20
}
{
   "userId":1,
   "number1":20,
   "number2":40
}

输出::地图

{
 "userId":1,
 "sum":90 // addition of all numbers associated with userId
}

我想使用Java 8流api。

我正在尝试这样,但这给了我错误,

  Map<Long, Long> hashMap  =results.stream().collect(Collectors.toMap(Numbers::userId,Collectors.summingLong(?));

所以我的问题是 我可以从Collectors.toMap()

调用以下方法吗
Long addNumbers(Long number1,Long number2){
return number1+number2;
}

1 个答案:

答案 0 :(得分:10)

使用Collectors::groupingBy和下游收集器是一种更简单的方法:

results.stream().collect(
     Collectors.groupingBy(
           Numbers::getUserId, Collectors.summingLong(x -> x.getNumber1() + x.getNumber2())
     )
);

您仍然可以使用Collectors.toMap来做到这一点:

results.stream().collect(
    Collectors.toMap(
         Numbers::getUserId,
         x -> x.getNumber1() + x.getNumber2(),
         Long::sum   
    )
);

或者没有流:

Map<Long, Long> all = new HashMap<>();
numbers.forEach(x -> all.merge(
                  x.getUserId(), 
                  x.getNumber1() + x.getNumber2(), 
                  Long::sum);