Skip to content

Instantly share code, notes, and snippets.

@kijanowski
Created November 17, 2018 20:43
Show Gist options
  • Select an option

  • Save kijanowski/941db548ad8bd2cd5389be4973d88ee2 to your computer and use it in GitHub Desktop.

Select an option

Save kijanowski/941db548ad8bd2cd5389be4973d88ee2 to your computer and use it in GitHub Desktop.
// instead of
public java.util.List<String> legacyFlatMap1(java.util.List<Optional<String>> args) {
return args
.stream()
.filter(Optional::isPresent)
.map(Optional::get)
.map(String::toLowerCase)
.collect(Collectors.toList());
}
// or
public java.util.List<String> legacyFlatMap2(java.util.List<Optional<String>> args) {
return args
.stream()
.flatMap(arg -> arg.map(Stream::of).orElseGet(Stream::empty))
.map(String::toLowerCase)
.collect(Collectors.toList());
}
// or
public java.util.List<String> legacyFlatMap3(java.util.List<Optional<String>> args) {
// since Java 9 introducing Optional.stream()
return args
.stream()
.flatMap(Optional::stream)
.map(String::toLowerCase)
.collect(Collectors.toList());
}
// do it the functional way
public io.vavr.collection.Seq vavrFlatMap(io.vavr.collection.Seq<Option<String>> args) {
return args
.flatMap(Function.identity()) // sames as .flatMap(arg -> arg)
.map(String::toLowerCase);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment