javajava-streamconditional-statements

NotNull Boolean value If else with Stream API


I wrote a single line code to make if else statement. I found it redundantly long. How can I make this line shorter and more efficient? isLocked is a boolean value here.

Stream.of( isLocked ).filter( x -> !x ).findFirst().orElseThrow( LimitLockException::new );

Solution

  • If you insist on using a library class to force this into a one-liner, Optional is slightly better suited than Stream (which ends up giving you an Optional anyway):

    Boolean isLocked = true;
    Optional.of(isLocked).filter(x -> ! x).orElseThrow(LimitLockException::new);
    

    I still don’t like it, though, and don‘t see the point. orElseThrow is for unexpectedly missing an element, a value that should be present. It’s not for something being locked. For throwing an exception in that case, I suggest that you prefer to have a throw statement conspicuously located on its own line. So use the if statement from Naman’s answer.

    There may be a wide-spread misconception that terseness of code is a goal. It’s not. Clarity is. Often the two go hand in hand, but not in this case (and if we had wanted brevity, the one-line if in Naman‘s answer would have beaten everything). The above code line is unnecessarily hard to decipher for a programmer knowing the use of Optional well and not having seen this code before.