Skip to content

Instantly share code, notes, and snippets.

@todvora
Created October 30, 2015 10:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save todvora/c04933a861a8f754560d to your computer and use it in GitHub Desktop.
Save todvora/c04933a861a8f754560d to your computer and use it in GitHub Desktop.
Lazy optional stream
package optional;
import java.util.Optional;
import java.util.function.Supplier;
import java.util.stream.Stream;
public class StreamOfOptional {
public static void main(String[] args) {
System.out.println("--Before eager--");
process(eager());
System.out.println("--After eager--");
System.out.println("--Before lazy--");
process(lazy());
System.out.println("--After lazy--");
};
private static void process(Stream<Optional<String>> stream) {
stream
.filter(Optional::isPresent).map(Optional::get) // if present, unpack
.peek(s -> System.out.println("processed: " + s)) // print, what is currently in the pipeline
.findFirst()
.ifPresent(System.out::println);
}
private static Stream<Optional<String>> lazy() {
// https://stackoverflow.com/a/28833677/3824515
return Stream.<Supplier<Optional<String>>>of(
() -> firstOpt(),
() -> secondOpt()
)
.map(Supplier::get);
}
private static Stream<Optional<String>> eager() {
return Stream.of(
firstOpt(),
secondOpt()
);
}
private static Optional<String> firstOpt() {
return Optional.ofNullable("first")
.map(s-> {
System.out.println("Cheap mapping on '"+s+"' done.");
return s;
});
}
private static Optional<String> secondOpt() {
return Optional.ofNullable("second")
.map(s-> {
System.out.println("Really expensive mapping on '"+s+"' done (e.g. DB access)!");
return s;
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment