Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoke method from stream api in java

I am novice to java 8.I am trying below scenario.

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
}

output:: Map

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

I want to use java 8 stream api.

I am trying like this but it gives me error,

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

So my question, Can i invoke below method from Collectors.toMap()

Long addNumbers(Long number1,Long number2){
return number1+number2;
}
like image 762
Ankita Goyal Avatar asked Sep 08 '18 20:09

Ankita Goyal


1 Answers

There is an easier way with Collectors::groupingBy with a downstream collector:

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

You can still do it with Collectors.toMap:

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

Or without streams :

Map<Long, Long> all = new HashMap<>();
numbers.forEach(x -> all.merge(
                  x.getUserId(), 
                  x.getNumber1() + x.getNumber2(), 
                  Long::sum);
like image 151
Eugene Avatar answered Oct 12 '22 07:10

Eugene