Skip to content

Instantly share code, notes, and snippets.

@will-molloy
Last active July 27, 2019 08:07
Show Gist options
  • Save will-molloy/55d4ba61fcaf4aada621e0a006759d69 to your computer and use it in GitHub Desktop.
Save will-molloy/55d4ba61fcaf4aada621e0a006759d69 to your computer and use it in GitHub Desktop.
Chaining Optional (Java 9 Optional#or)
import java.util.Optional;
class ChainingOptional {
static Optional<Integer> get1() {
return Optional.empty();
}
static Optional<Integer> get2() {
return Optional.empty();
}
static Optional<Integer> get3() {
return Optional.of(3);
}
public static void main(String[] args) {
var integer = get1().or(() -> get2()).or(() -> get3()).orElseThrow();
System.out.println(integer); // 3
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment