Created
April 18, 2018 13:06
-
-
Save soverby/52ce68a73d4071bfa3c7c008acd2d370 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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