Java Stream How to - Create Optional String value








Question

We would like to know how to create Optional String value.

Answer

import java.util.Optional;
/* w  ww.  j  av a 2 s.  co  m*/
public class Main {

    public static void main(String[] args) {
        Optional<String> optional = Optional.of("bam");

        optional.isPresent();           // true
        optional.get();                 // "bam"
        optional.orElse("fallback");    // "bam"

        optional.ifPresent((s) -> System.out.println(s.charAt(0)));     // "b"
    }

}

The code above generates the following result.