Skip to content

Instantly share code, notes, and snippets.

@ugandapinik
Created August 13, 2022 02:10
Show Gist options
  • Save ugandapinik/ca4906964aadd06d22af5f99d6aac8d5 to your computer and use it in GitHub Desktop.
Save ugandapinik/ca4906964aadd06d22af5f99d6aac8d5 to your computer and use it in GitHub Desktop.
JAVA OPTIONAL CLASS
public static void main(String[] args) {
Optional<String> hello = Optional.ofNullable(null);
// 1. Optional Use:
// check value is present in hello
System.out.println(hello.isPresent());
// check if hello(v) is empty
System.out.println(hello.isEmpty());
// 2. orElse: if hello doesn't contain any value
// then $hello = world
String orElse = hello
.map(String::toUpperCase)
.orElseGet(() -> {
//.. extra computation to retrieve the value
return "world";
});
System.out.println(orElse);
// 3. check if hello exists
// otherwise world will display.
hello.ifPresentOrElse(System.out::println, () -> System.out.println("World"));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment