Java Optional check if there is a value in Optional
import java.util.Optional; public class Main { public static void main(String[] args) { Optional<String> str = Optional.of("your value"); if (str.isPresent()) { String value = str.get();//ww w . j a v a 2 s . co m System.out.println("Optional contains " + value); } else { System.out.println("Optional is empty."); } String o = null; str = Optional.ofNullable(o); if (str.isPresent()) { String value = str.get(); System.out.println("Optional contains " + value); } else { System.out.println("Optional is empty."); } } }
The following code passes in Consumer
function to Optional.ifPresent()
.
import java.util.Optional; public class Main { public static void main(String[] args) { Optional<String> str = Optional.of("AAA"); str.ifPresent(value -> System.out.println("Optional contains " + value)); //from www . j a v a 2s .co m String o = null; str = Optional.ofNullable(o); str.ifPresent(value -> System.out.println("Optional contains " + value)); } }