Creating an Optional

The Optional<T> class models the absence of a value by a special singleton returned by the Optional.empty() method. In contrast to the null value, this singleton is a viable Optional object on which methods of the Optional class can be invoked without a NullPointerException being thrown.

Click here to view code image

static <T> Optional<T> empty()
static <T> Optional<T> of(T nonNullValue)
static <T> Optional<T> ofNullable(T value)

The empty() method returns an empty Optional instance; that is, it indicates the absence of a value.

The of() method returns an Optional with the specified value, if this value is non-null. Otherwise, a NullPointerException is thrown.

The ofNullable() method returns an Optional with the specified value, if this value is non-null. Otherwise, it returns an empty Optional.

The static Optional.of() factory method creates an Optional that encapsulates the non-null argument specified in the method call, as in the first declaration below. However, if the argument is a null value, a NullPointerException is thrown at runtime, as in the second declaration.

Click here to view code image

Optional<String> blurb0 = Optional.of(“Java Programmers tell all!”);
Optional<String> xblurb = Optional.of(null);   // NullPointerException

The static Optional.ofNullable() factory method also creates an Optional that encapsulates the non-null argument specified in the method call, as in the first declaration below. However, if the argument is a null value, the method returns an empty Optional, as in the second declaration—which is effectively the same as the third declaration below.

Click here to view code image

Optional<String> blurb1 = Optional.ofNullable(“Program like a Java Pro!”);
Optional<String> noBlurb2 = Optional.ofNullable(null);   // Optional.empty()
Optional<String> noBlurb3 = Optional.empty();

The blurbs above are used to initialize two Book objects (book0, book1) in Example 16.8. These Book objects with optional blurbs will be used to illustrate how to use Optional objects.

Example 16.8 Using Optionals

Click here to view code image

// File: OptionalUsage.java
import java.util.Optional;
// A book can have an optional blurb.
class Book {
  private String bookName;
  private Optional<String> optBlurb;
  public String getBookName() { return bookName; }
  public Optional<String> getOptBlurb() { return optBlurb; }
  public Book(String bookName, Optional<String> optBlurb) {
    this.bookName = bookName;
    this.optBlurb = optBlurb;
  }
}
// A course can have an optional book.
class Course {
  private Optional<Book> optBook;
  public Optional<Book> getOptBook() { return optBook; }
  public Course(Optional<Book> optBook) { this.optBook = optBook; }
}
public class OptionalUsage {
  public static void main(String[] args) {
    // Creating an Optional:
    Optional<String> blurb0 = Optional.of(“Java Programmers tell all!”);
    //Optional<String> xblurb = Optional.of(null);   // NullPointerException
    Optional<String> blurb1 = Optional.ofNullable(“Program like a Java Pro!”);
    Optional<String> noBlurb2 = Optional.ofNullable(null);   // Optional.empty()
    Optional<String> noBlurb3 = Optional.empty();
    // Create some books:
    Book book0 = new Book(“Embarrassing Exceptions”, blurb0);
    Book book1 = new Book(“Dancing Lambdas”, noBlurb2);      // No blurb.
    // Querying an Optional:
    if (book0.getOptBlurb().isPresent()) {
      System.out.println(book0.getOptBlurb().get());//Java Programmers tell all!
    }
    book0.getOptBlurb()
         .ifPresent(System.out::println);           //Java Programmers tell all!
//  System.out.println(book1.getOptBlurb().get());  // NoSuchElementException
    String blurb = book0.getOptBlurb()
                        .orElse(“No blurb”);     // “Java Programmers tell all!”
    System.out.println(blurb);
    blurb = book1.getOptBlurb().orElse(“No blurb”);          // “No blurb”
    System.out.println(blurb);
    blurb = book1.getOptBlurb().orElseGet(() -> “No blurb”); // “No blurb”
    System.out.println(blurb);
    //blurb = book1.getOptBlurb()                            // RuntimeException
    //             .orElseThrow(() -> new RuntimeException(“No blurb”));
  }
}

Output from the program: Java Programmers tell all!
Java Programmers tell all!

Java Programmers tell all!
No blurb
No blurb

Leave a Reply

Your email address will not be published. Required fields are marked *