Optionals are not functional interfaces, but nifty utilities to prevent NullPointerException. It’s an important concept for the next section, so let’s have a quick look at how Optionals work.

Optional is a simple container for a value which may be null or non-null. Think of a method which may return a non-null result but sometimes return nothing. Instead of returning null you return an Optional in Java 8.

  1. Optional<String> optional =Optional.of("bam");
  2. optional.isPresent();// true
  3. optional.get();// "bam"
  4. optional.orElse("fallback");// "bam"
  5. optional.ifPresent((s)->System.out.println(s.charAt(0)));// "b"