Quantcast
Channel: Baeldung
Viewing all articles
Browse latest Browse all 4536

Transforming an Empty String into an Empty Optional

$
0
0

1. Introduction

In this quick tutorial, we’ll present different ways to transform a null or empty String into an empty Optional.

Getting an empty Optional out of null is straightforward — we just use Optional.ofNullable(). But, what if we want empty Strings to work this way as well?

So, let’s explore some different options for converting an empty String into an empty Optional.

2. Using Java 8

In Java 8, we can leverage the fact that if an Optional#filter‘s predicate isn’t met, then it returns an empty Optional:

@Test
public void givenEmptyString_whenFilteringOnOptional_thenEmptyOptionalIsReturned() {
    String str = "";
    Optional<String> opt = Optional.ofNullable(str).filter(s -> !s.isEmpty());
    Assert.assertFalse(opt.isPresent());
}

And we don’t even need to check for null here since ofNullable will short-circuit for us in cases where str is null.

Creating a special lambda for the predicate is a bit cumbersome, though. Can’t we get rid of it somehow?

3. Using Java 11

The answer to the above wish doesn’t actually come until Java 11.

In Java 11, we’ll still use Optional.filter(), but Java 11 introduces a new Predicate.not() API that makes it easy to negate method references.

So, let’s simplify what we did earlier, now using a method reference instead:

@Test
public void givenEmptyString_whenFilteringOnOptionalInJava11_thenEmptyOptionalIsReturned() {
    String str = "";
    Optional<String> opt = Optional.ofNullable(str).filter(Predicate.not(String::isEmpty));
    Assert.assertFalse(opt.isPresent());
}

4. Using Guava

We can also use Guava to satisfy our needs. However, in that case, we’ll use a slightly different approach.

Instead of calling a filter method on an outcome of Optional#ofNullable, we’ll first convert an empty String to null using Guava’s String#emptyToNull and only then pass it to Optional#ofNullable:

@Test
public void givenEmptyString_whenPassingResultOfEmptyToNullToOfNullable_thenEmptyOptionalIsReturned() {
    String str = "";
    Optional<String> opt = Optional.ofNullable(Strings.emptyToNull(str));
    Assert.assertFalse(opt.isPresent());
}

5. Conclusion

In this short article, we’ve explored different ways to transform an empty String to an empty Optional.

As usual, the examples used in this article can be found in our GitHub project.


Viewing all articles
Browse latest Browse all 4536

Trending Articles