Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a value if not null within a java stream

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();
    }
like image 914
serah Avatar asked Jun 14 '26 07:06

serah


1 Answers

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();
like image 175
Andronicus Avatar answered Jun 16 '26 20:06

Andronicus