Java Stream How to - Output value if present in an Optional








Question

We would like to know how to output value if present in an Optional.

Answer

import java.util.Optional;
/*from   w  w  w .j  a  v  a  2s.  c om*/
public class Main {
   public static void main(String[] args) {
     Optional<String> optional1 = Optional.empty();
     Optional<String> optional2 = Optional.of("DEMO");

     System.out.println("optional2.get = " + optional2.get());
     System.out.println("optional1.orElse = " + optional1.orElse("Something else"));
     optional2.ifPresent(System.out::println);
     System.out.println("optional1.isPresent = " + optional1.isPresent());

   }

}

The code above generates the following result.