50

Given a String I need to get an Optional, whereby if the String is null or empty the result would be Optional.empty. I can do it this way:

String ppo = "";
Optional<String> ostr = Optional.ofNullable(ppo);
if (ostr.isPresent() && ostr.get().isEmpty()) {
    ostr = Optional.empty();
}

But surely there must be a more elegant way.

assylias
  • 310,138
  • 72
  • 642
  • 762
Germán Bouzas
  • 1,390
  • 1
  • 12
  • 18
  • If you can live with it returning an empty String instead of Optional.empty you could do this: Optional.ofNullable(ppo).orElse(""); – acvcu Jun 22 '16 at 17:37

6 Answers6

93

You could use a filter:

Optional<String> ostr = Optional.ofNullable(ppo).filter(s -> !s.isEmpty());

That will return an empty Optional if ppo is null or empty.

assylias
  • 310,138
  • 72
  • 642
  • 762
  • in latest version of java you can just `Optional.ofNullable(s).filter(Predicate.not(String::isEmpty))` as written in this answer https://stackoverflow.com/a/53212977/1636173 – Giulio Caccin Nov 11 '21 at 09:18
19

With Apache Commons:

.filter(StringUtils::isNotEmpty)
Feeco
  • 4,518
  • 7
  • 29
  • 64
  • My case was that I couldn't take even for blanks, so used StringUtils.isNotBlank - however approach is same. thanks. – Raj Jun 06 '19 at 01:44
  • from java 11 you dont need apache commons anymore, just use `.filter(Predicate.not(String::isBlank))` – Giulio Caccin Nov 11 '21 at 09:31
11

Java 11 answer:

var optionalString = Optional.ofNullable(str).filter(Predicate.not(String::isBlank));

String::isBlank deals with a broader range of 'empty' characters.

Michael Barnwell
  • 704
  • 1
  • 11
  • 16
3

How about:

Optional<String> ostr = ppo == null || ppo.isEmpty()
    ? Optional.empty()
    : Optional.of(ppo);

You can put that in a utility method if you need it often, of course. I see no benefit in creating an Optional with an empty string, only to then ignore it.

Jon Skeet
  • 1,335,956
  • 823
  • 8,931
  • 9,049
  • @assylias: Fixed. It's never clear to me in Java how type inference works with the conditional operator. (Or rather, I never remember...) – Jon Skeet Feb 04 '15 at 13:25
  • 1
    With Java 8 it has become very rare that you need it. – assylias Feb 04 '15 at 13:28
  • 1
    from java 11 you can keep concatenating with filter and predicate, no other dependencies are needed: `Optional.ofNullable(s).filter(Predicate.not(String::isEmpty))` as written in this answer https://stackoverflow.com/a/53212977/1636173 – Giulio Caccin Nov 11 '21 at 09:33
2

You can use map :

String ppo="";
Optional<String> ostr = Optional.ofNullable(ppo)
                                .map(s -> s.isEmpty()?null:s);
System.out.println(ostr.isPresent()); // prints false
Eran
  • 374,785
  • 51
  • 663
  • 734
2

If you use Guava, you can just do:

Optional<String> ostr = Optional.ofNullable(Strings.emptyToNull(ppo));