Can this be converted to stream one-liner?

Georg :

I am wondering if this could be written more neatly as a stream function:

MyObject myObject = new MyObject();

for (Thing thing : listofThings) {
    myObject = myObject.combine(thing);
}
Eran :

Yes, using a Stream with reduce:

MyObject myObject = listofThings.stream()
                                .reduce(new MyObject(),
                                        MyObject::combine,
                                        MyObject::combiner);

where combiner is a MyObject method that takes another MyObject instance and combines it into the current object.

As an alternative, you can first map the Thing instances to MyObject instances, and then reduce these instances to a single MyObject instance:

MyObject myObject = listofThings.stream()
                                .map(new MyObject()::combine)
                                .reduce(MyObject::combiner)
                                .orElseGet(MyObject::new);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=112540&siteId=1