Skip to content

Instantly share code, notes, and snippets.

@zaltoprofen
Last active August 29, 2015 13:58
Show Gist options
  • Save zaltoprofen/10335183 to your computer and use it in GitHub Desktop.
Save zaltoprofen/10335183 to your computer and use it in GitHub Desktop.
import java.util.function.*;
import java.util.Arrays;
import java.util.stream.Collectors;
public class WrapFunc{
public static void main (String[] args) {
Arrays.stream(args).map(Integer::parseInt).map(Throwables.ignore(WrapFunc::fib))
.forEach(Throwables.ignore(WrapFunc::myPrint));
}
static int fib(int x) throws Exception{
System.out.println(String.format("Called fib(%d)", x));
return fib_(x);
}
static int fib_(int x){
if (x == 0 || x == 1) return x;
return fib_(x-1) + fib_(x-2);
}
static int count = 0;
static void myPrint(int i) throws Exception {
if(count++ % 5 == 0){
throw new Exception();
}else{
System.out.println(i);
}
}
}
@FunctionalInterface
interface IgnoreExceptionFunction<T,R> extends Function<T,R>{
public R func(T arg) throws Exception;
public default R apply(T arg){
try {
return func(arg);
} catch (Exception e) {
return null;
}
}
}
@FunctionalInterface
interface IgnoreExceptionConsumer<T> extends Consumer<T>{
public void consumer(T arg) throws Exception;
public default void accept(T arg){
try {
consumer(arg);
} catch (Exception e) { }
}
}
class Throwables{
static <T, R> Function<T,R> ignore(IgnoreExceptionFunction<T,R> func){
return func;
}
static <T> Consumer<T> ignore(IgnoreExceptionConsumer<T> consumer){
return consumer;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment