Java Stream How to - Exercise Optional method and value








Question

We would like to know how to exercise Optional method and value.

Answer

//from w w w.  jav a  2 s.co m
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

public class Main {
  public static void main(String[] args) {

    Optional<String> value = Optional.of("some value");
    System.out.println(value.isPresent());
    System.out.println(value.get());
    String str = null;
   // Optional.of(str);

    Optional<Integer> o = Optional.empty();
    System.out.println(o.isPresent());
    System.out.println(o.orElse(42));

    List<Integer> results = new ArrayList<>();
    Optional<Integer> second = Optional.of(3);
    second.ifPresent(results::add); // must operate via side-effects,
                                    // unfortunately...
    System.out.println(results);

    o = Optional.empty();
    System.out.println(o.orElse(42));

    o = Optional.of(42);
    System.out.println(o.get());

    o = Optional.empty();
    o.get();
  }

}