Skip to content

Instantly share code, notes, and snippets.

@soverby
Created April 18, 2018 13:06
Show Gist options
  • Save soverby/52ce68a73d4071bfa3c7c008acd2d370 to your computer and use it in GitHub Desktop.
Save soverby/52ce68a73d4071bfa3c7c008acd2d370 to your computer and use it in GitHub Desktop.
public class OptionalChainingComposed {
public static void main(String[] args) {
OptionalChainingComposed optionalChaining = new OptionalChainingComposed();
optionalChaining.happyPath();
optionalChaining.nullInput();
}
public void happyPath() {
nonNullPipeline("happyPath")
.ifPresent(System.out::println);
}
public void nullInput() {
nonNullPipeline(null).ifPresent(val -> val.concat("boom!"));
}
// Instead of THIS:
// public Optional<String> nonNullPipeline(String string) {
// return Optional.ofNullable(stringOptional)
// .map(val -> operation1.apply(val))
// .map(val -> operation2.apply(val))
// .map(val -> operation3.apply(val));
// }
// put these here so we don't get an illegal forward reference...
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;
// We can do THIS:
Function<String, String> pipelineOne = operation1.andThen(operation2).andThen(operation3);
// And this:
public Optional<String> nonNullPipeline(String string) {
return Optional.ofNullable(string).map(pipelineOne);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment