Below is the simplified structure of my classes:
public class Thing {
private BigDecimal field1;
private BigDecimal field2;
private XYZ field3;
private BigDecimal field4;
}
public class XYZ {
private BigDecimal field5;
private BigDecimal field6;
}
I need to sum up the following fields field1
, field2
and field3.field5
(i.e. property field5
of the XYZ
object). All of them can be null
including field3
.
I've implemented this logic in the way shown below, but it lucks the null-check field3
, how can it be implemented?
My code:
public BigDecimal addFields(List<Thing> things) {
return things.parallelStream()
.flatMap(thing -> Stream.of(thing.getField1(),
thing.getField2(),
thing.getField3().getField5()))
.reduce(BigDecimal.ZERO, BigDecimal::add);
}