John
John

Reputation: 5287

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:

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

Upvotes: 4

Views: 250

Answers (2)

Tagir Valeev
Tagir Valeev

Reputation: 100199

If your A objects are mutable, then more efficient solution is possible which is based on collect() method. Add a method to A which describes the merging strategy:

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

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

Now you can write

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

This way you will not have to create intermediate A object for every reduction step: single common object will be reused instead.

Upvotes: 5

Alexis C.
Alexis C.

Reputation: 93842

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

Upvotes: 7

Related Questions