combinedResult is a stream of type ObjectNode that consists of data like this for example:
{"id":"id1","version":1,"Success":4,"Exception":6,"Failure":3}
{"id":"id1","version":1,"Success":4,"Exception":6,"Failure":3}
{"id":"id1","version":2,"Exception":1,"Success":2,"Failure":2}
{"id":"id1","version":2,"Exception":1,"Success":2,"Failure":2}
I want to get a result like this:
{"id":"id1","version":1,"Success":8,"Exception":12,"Failure":6}
{"id":"id1","version":2,"Success":4,"Exception":2,"Failure":4}
I have written the below BinaryOperator function
BinaryOperator<ObjectNode> func = (o1, o2) -> {
if (o1.get("id").asText().equals(o2.get("id").asText()) &&
o1.get("version").equals(o2.get("version"))) {
ObjectNode o = Jive.newObjectNode();
o.set("id", Jive.newJsonNode(o1.get("id")));
o.set("version", Jive.newJsonNode(o1.get("version")));
o.set("Success", Jive.newJsonNode(o1.get("Success").asInt() + o2.get("Success").asInt()));
o.set("Failure", Jive.newJsonNode(o1.get("Failure").asInt() + o2.get("Failure").asInt()));
o.set("Exception", Jive.newJsonNode(o1.get("Exception").asInt() + o2.get("Exception").asInt()));
return o;
}
return o1;
};
combinedResult.stream().reduce(func)
But when I try this out, I get below result:
Optional[{"id":"id1","version":1,"Success":8,"Failure":6,"Exception":12}]
I understand that this is because I return o1 as default value in the BinaryOperator, but I don't know how to resolve this.
You can use reduce method.
Your have start identity with a empty HashMap whose key will be unique identifier on which you wanted to cumulate results. (Id + Version)
But ideal way as Sudipta Bhattacharyya and Holger mentioned is to use
collectBelow is snippet of solution.