Java Stream How to - Get value or default from Optional








Question

We would like to know how to get value or default from Optional.

Answer

import java.util.Optional;

public class Main {

  public static void main(String[] args) {
    Optional<Integer> o = Optional.empty();
    System.out.println(o.orElse(42));
  }
}

The code above generates the following result.