home

Optional

Overview

Creating Optionals

Optional.of(new Integer(1));         // Optional[1]
Optional.ofNullable(new Integer(1)); // Optional[1]
Optional.empty();                    // Optional.empty

Optional.of(null);                   // NullPointerException
Optional.ofNullable(null);           // Optional.empty

Reading Optionals

Querying Optionals

Optional.of(1).isPresent();     // true
Optional.empty().isPresent();   // false

Getting Values from Optionals

Optional.get()

Optional.of(1).get();   // 1
Optional.empty().get(); // NoSuchElementException

Optional.orElse()

Optional.of(1).orElse(2);   // 1
Optional.empty().orElse(2)  // 2

Extracting Information with map and flatMap

class F {
    String f;
    F (String f) {this.f = f;}
    String getF() {return f;}
}

Optional.of(new F("F")).map(F::getF);  // Optional<String>[F]
Optional.of(new F(null)).map(F::getF); // Optional<String>empty
Optional.<F>empty().map(F::getF);      // Optional<String>empty
class Bar {}

class Foo {
    Optional<Bar> bar = Optional.empty();
    Optional<Bar> getBar() {return bar;}
}

Foo foo = new Foo();
Optional.of(foo).map(Foo::getBar);      // Optional[Optional.empty]
Optional.of(foo).flatMap(Foo::getBar);  // Optional.empty

Filtering Optionals

Optional.of(1).filter(i -> i > 5);  // Optional.empty
Optional.of(6).filter(i -> i > 5);  // Optional[6]

Consuming Optionals with ifPresent

class Foo {
    int i;
}

int i = 5;
Foo foo = new Foo();
Optional.of(foo).ifPresent(aFoo -> aFoo.i = i);                 // foo.i is 5
Optional.<Foo>ofNullable(null).ifPresent(aFoo -> aFoo.i = i);   // Nothing happens

// Remember this will not compile:
// Optional.of(foo).ifPresent(aFoo -> i = aFoo.i);
// error: local variables referenced from a lambda expression must be final or effectively final