Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In java 8 using stream API, how to return instance from Map with multiple calculations required

Suppose there is class like this:

class A {

    long sent;
    long received;
    double val; // given as max {(double)sent/someDenominator,(double)received/someDenominator}
}

of which there are number of instance references in Map<String , A>.

Is it possible in one go, using stream API, to return instance of class A with following properties:

  • sent = sum of sent fields from all instances
  • received = sum of received fields from all instances in Map
  • val = maximum value of val, given all entries where val = max {sent/someDenominator,received/someDenominator}

What would be trivial task using standard for loop and one iteration, i don't have a clue how to achieve with stream API.

like image 628
John Avatar asked Dec 15 '22 08:12

John


1 Answers

You could use reduce:

Optional<A> a = map.values()
                   .stream()
                   .reduce((a1, a2) -> new A(a1.sent + a2.sent, a1.received + a2.received, Math.max(a1.val, a2.val)));
like image 193
Alexis C. Avatar answered Apr 10 '23 16:04

Alexis C.