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

Suppose there is a class:

class A {

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

of which there are a number of references to instances in Map<String , A>.

Is it possible in one motion, using the stream API, to return an instance of class A with the 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 a trivial task using the standard for a loop and one iteration, I don’t know how to achieve using the stream API.

+4
source share
2

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)));
+7

A , , collect(). A, :

class A {
    long sent;
    long received;
    double val;

    void merge(A other) {
        sent += other.sent;
        received += other.received;
        val = Math.max(val, other.val);
    }
}

A a = map.values().stream().collect(A::new, A::merge, A::merge);

A : .

+5

Source: https://habr.com/ru/post/1628488/


All Articles