Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I do something if an Optional<String> is not present or present but an empty string?

I can't seem to figure out a more concise way to do this

Optional<String> foo;
if (!foo.isPresent() || StringUtils.isBlank(foo.get())) {
  // ...
}

There's this but it actually makes the logic more convoluted, IMO:

Optional<String> foo;
if (!foo.filter(StringUtils::isNotBlank).isPresent()) {
  // ...
}

Feel like I'm missing something really obvious.

like image 437
slackwing Avatar asked Dec 24 '22 01:12

slackwing


1 Answers

Maybe this is what you're looking for.

Optional.of("")
        .filter(not(String::isBlank)))
        .orElseThrow(() -> new MyException("..."));

You'll find not under Predicate.

Obviosuly this is less efficient than having an if statement, but it has its place.

Ah, ok, after your comment it is more clear. Use orElseThrow.

like image 95
LppEdd Avatar answered Jan 13 '23 13:01

LppEdd