spakai
spakai

Reputation: 303

Optional IfPresent and alternative else

How can i make a single code that will either set type to BYTES or SECONDS. Here I am setting a default BYTES before overwritting it with SECONDS with the setTypeAsSecondsIfCcTimeIsValid function call

    } else if (mscc.getRsu().isPresent()) {
        type = Type.BYTES;
        mscc.getRsu().get().getCcTime().ifPresent(this::setTypeAsSecondsIfCcTimeIsValid);
    }

Upvotes: 1

Views: 1855

Answers (1)

Tagir Valeev
Tagir Valeev

Reputation: 100149

Something like this should work:

type = mscc.getRsu().flatMap(rsu -> rsu.getCcTime())
                    .filter(ccTime -> isCcTimeValid(ccTime))
                    .map(ccTime -> Type.BYTES).orElse(Type.SECONDS);

However I would use ternary instead:

type = mscc.getRsu().flatMap(rsu -> rsu.getCcTime())
                    .filter(ccTime -> isCcTimeValid(ccTime))
                    .isPresent() ? Type.BYTES : Type.SECONDS;

This code assumes that you have isCcTimeValid method.

Upvotes: 3

Related Questions