Skip to content

Instantly share code, notes, and snippets.

@ojitha
Last active November 23, 2019 06:29
Show Gist options
  • Select an option

  • Save ojitha/c01a4ea880a3389217ba69b20f188a8e to your computer and use it in GitHub Desktop.

Select an option

Save ojitha/c01a4ea880a3389217ba69b20f188a8e to your computer and use it in GitHub Desktop.
This example shows how to wrap a Java lambdafunction to avoide any exception.
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Stream;
@FunctionalInterface
interface ExFunction<E, F> {
F apply (E e) throws Throwable;
static <E, F> Function<E, Optional<F>> wrap (ExFunction<E, F> op){
return e -> {
try {
return Optional.of(op.apply(e));
} catch (Throwable throwable) {
System.out.println("Error");
return Optional.empty();
}
};
}
}
Stream.of("a.txt", "b.txt","/Users/ojitha/Library/Preferences/IntelliJIdea2019.2/consoles/jshell/jshell_console_1.snippet")
.map(ExFunction.wrap(f -> Files.lines(Paths.get(f))))
.filter(Optional::isPresent)
.flatMap(opt -> opt.get()).forEach(System.out::println);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment