When we’re writing our own code that produces Optionals, there are three static methods we can use:
- empty() : Produces an Optional with nothing inside.
- of(value) : If we already know that value is not null , use this to wrap it in an Optional.
- ofNullable(value) : Use this if we don’t know that value is not null . It automatically produces Optional.empty if value is null, and otherwise wraps value inside an Optional.
// streams/CreatingOptionals.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
import java.util.*;
import java.util.function.*;
import java.util.stream.*;
class CreatingOptionals {
static void test(String testName, Optional<String> opt) {
System.out.println(" === " + testName + " === ");
System.out.println(opt.orElse("Null")); // the value, if present, otherwise other(Null)
}
public static void main(String[] args) {
test("empty", Optional.empty()); // A container object which may or may not
// contain a non-null value. If a value is present, isPresent() will return true
// and get() will return the value.
// final class Optional sine 1.8
test("of", Optional.of("Howdy"));
try {
test("of", Optional.of(null));
} catch (Exception e) {
System.out.println(e);
}
test("ofNullable", Optional.ofNullable("Hi"));
test("ofNullable", Optional.ofNullable(null));
}
}
/* Output:
=== empty ===
Null
=== of ===
Howdy
java.lang.NullPointerException
=== ofNullable ===
Hi
=== ofNullable ===
Null
*/
references:
1. On Java 8 - Bruce Eckel
2. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/streams/CreatingOptionals.java
3. https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html#orElse-T-
4. https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html#of-T-
5. https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html#ofNullable-T-
6. http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/util/Optional.java