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

Andrew Cheong :

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.

LppEdd :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=73085&siteId=1