How can I handle null checks in the below code using Java 8 when my counterparty can be null.
I want to set counterParty only if it has a value and not set if it is empty.
public static Iterable<? extends Trade> buildTrade (final List<Trade> trade) {
return () -> trade.stream()
.map(trade -> Trade.newBuilder()
.setType(trade.type())
.setUnit(trade.unit())
.setCounterParty(trade.counterParty())
.build())
.iterator();
}
You can use the following code:
trade.stream()
.map(trade -> {
TradeBuilder tb = Trade.newBuilder()
.setType(trade.type())
.setUnit(trade.unit());
Optional.ofNullable(trade.counterParty())
.ifPresent(tb::setCounterParty);
return tb.build();
})
.iterator();
Or without Optional:
trade.stream()
.map(trade -> {
TradeBuilder tb = Trade.newBuilder()
.setType(trade.type())
.setUnit(trade.unit());
if(trade.counterParty() != null) tb.setCounterParty(trade.counterParty());
return tb.build();
})
.iterator();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With