54

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
  • 321,522
  • 82
  • 660
  • 783
Germán Bouzas
  • 1,430
  • 1
  • 13
  • 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

7 Answers7

102

You could use a filter:

Optional.ofNullable(s).filter(not(String::isEmpty));

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

Giulio Caccin
  • 2,962
  • 6
  • 36
  • 57
assylias
  • 321,522
  • 82
  • 660
  • 783
22

With Apache Commons:

.filter(StringUtils::isNotEmpty)
Boris
  • 4,944
  • 7
  • 36
  • 69
  • 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
13

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
  • 724
  • 1
  • 10
  • 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,421,763
  • 867
  • 9,128
  • 9,194
  • @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
  • 387,369
  • 54
  • 702
  • 768
2

If you use Guava, you can just do:

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

Another option using filter

Optional<String> ostr = Optional.ofNullable(ppo).filter(o -> !o.isBlank());
Pepe N O
  • 1,678
  • 1
  • 7
  • 11