Skip to content

Instantly share code, notes, and snippets.

@soverby
Last active April 18, 2018 12:53
Show Gist options
  • Save soverby/2851342d76cd6e65ca638ec765f0659f to your computer and use it in GitHub Desktop.
Save soverby/2851342d76cd6e65ca638ec765f0659f to your computer and use it in GitHub Desktop.
public class OptionalChaining {
public static void main(String[] args) {
OptionalChaining optionalChaining = new OptionalChaining();
optionalChaining.happyPath();
optionalChaining.nullInput();
optionalChaining.thereBeNullsHereOne();
optionalChaining.thereBeNullsHereTwo();
}
// Happy path with a pipeline that doesn't return nulls
public void happyPath() {
nonNullPipeline("happyPath")
.ifPresent(System.out::println);
}
// Pass in a null, no problem (and no null checks)
public void nullInput() {
nonNullPipeline(null).ifPresent(val -> val.concat("boom!"));
}
// Pipeline with a null response in the first unit
public void thereBeNullsHereOne() {
prefixNullPipeline("thereBeNullsHereOne")
.ifPresent(System.out::println);
}
// Pipeline with a null response in the middle
public void thereBeNullsHereTwo() {
randomNullPipeline("thereBeNullsHereTwo")
.ifPresent(System.out::println);
}
public Optional<String> nonNullPipeline(String stringOptional) {
return Optional.ofNullable(stringOptional)
.map(val -> operation1.apply(val))
.map(val -> operation2.apply(val))
.map(val -> operation3.apply(val));
}
public Optional<String> prefixNullPipeline(String stringOptional) {
return Optional.ofNullable(stringOptional)
.map(val -> operation4.apply(val)) // Null returned here!!
.map(val -> operation1.apply(val))
.map(val -> operation2.apply(val))
.map(val -> operation3.apply(val));
}
public Optional<String> randomNullPipeline(String stringOptional) {
return Optional.ofNullable(stringOptional)
.map(val -> operation1.apply(val))
.map(val -> operation4.apply(val)) // Null returned here!!
.map(val -> operation2.apply(val))
.map(val -> operation3.apply(val));
}
Function<String, String> operation1 = String::toLowerCase;
Function<String, String> operation2 = String::toUpperCase;
Function<String, String> operation3 = value -> value.concat("suffix");
Function<String, String> operation4 = value -> null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment