The Optional class (java.util.Optional) is a container class that represents the presence or absence of a value. Null-pointer exceptions can also be avoided. Here’s a look at some common methods for the Optional class.

1.of()

Create an Optional instance for non-null values

Optional<String> op1 = Optional.of("helloOptional");
Optional<String> op2 = Optional.of(null); // Throw an exception
Copy the code

What if I want to create a container for NULL? Moving on…

2.isPresent()

Return true if the value exists, false otherwise

System.out.println(op1.isPresent()); / / output true
Copy the code

3.get()

Returns the object, possibly null

System.out.println(op1.get()); / / output helloOptional
Copy the code

4.OfNullable()

Returns an empty Optional if the specified value is null

Optional<String> op2 = Optional.ofNullable(null);
System.out.println(op2.isPresent()); / / output is false
Copy the code

5.ifPresent()

If the instance is not empty, the Comsumer Lambda expression is called

public void ifPresent(Consumer<? super T> consumer) {
    if(value ! =null)
        consumer.accept(value);
}
Copy the code

Use:

Optional<String> op1 = Optional.of("Hello"); op1.ifPresent((s) -> { System.out.println(s); // print Hello});Copy the code

6.map()

If the instance is not empty, call the Function Lambda expression

public<U> Optional<U> map(Function<? super T, ? extends U> mapper) {
    Objects.requireNonNull(mapper);
    if(! isPresent())return empty();
    else {
        returnOptional.ofNullable(mapper.apply(value)); }}Copy the code

Use:

Optional<String> op1 = Optional.of("Hello");
Optional<String> op2 = op1.map((s) -> s.toUpperCase());
op2.ifPresent((s) -> {
    System.out.println(s); HELLO / / output
});
Copy the code

7.orElse(obj)

Return the instance if it is not empty, obj otherwise

Optional<String> op1 = Optional.of("Hello");
System.out.println(op1.orElse("World")); Hello / / output
Optional<String> op2 = Optional.ofNullable(null);
System.out.println(op2.orElse("World")); / / output World
Copy the code

8.orElseGet(Supplier<? extends T> other)

Returns the instance if it is not empty, otherwise returns Supplier

Optional<String> op1 = Optional.of("Hello");
System.out.println(op1.orElseGet(() -> {return new String("World"); }));Hello / / output
Optional<String> op2 = Optional.ofNullable(null);
System.out.println(op2.orElseGet(() -> {return new String("World"); }));/ / output World
Copy the code