Last active
November 23, 2019 06:29
-
-
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.
This file contains hidden or 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
| 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