Skip to content
Advertisement

How to use Java reduce() function on stream of objects with BinaryOperator

combinedResult is a stream of type ObjectNode that consists of data like this for example:

JavaScript

I want to get a result like this:

JavaScript

I have written the below BinaryOperator function

JavaScript

But when I try this out, I get below result:

JavaScript

I understand that this is because I return o1 as default value in the BinaryOperator, but I don’t know how to resolve this.

Advertisement

Answer

You can use reduce method.

JavaScript

Your have start identity with a empty HashMap whose key will be unique identifier on which you wanted to cumulate results. (Id + Version)

JavaScript

But ideal way as Sudipta Bhattacharyya and Holger mentioned is to use collect

Below is snippet of solution.

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement