jdk8函数式编程用的很爽
但是遇到需要处理异常就很尴尬,需要这么写:
List<Integer> integers = Arrays.asList(3, 9, 7, 0, 10, 20);
integers.forEach(i -> {
try {
System.out.println(50 / i);
} catch (ArithmeticException e) {
System.err.println(
"Arithmetic Exception occured : " + e.getMessage());
}
});
这种写法感觉不优雅,原本我们只是想把异常抛出方法,不想要处理。
可以改成如下写法:
List<Integer> integers = Arrays.asList(3, 9, 7, 0, 10, 20);
integers.forEach(throwingConsumerWrapper(i -> System.out.println(50 / i)));
@FunctionalInterface
public interface ThrowingConsumer<T, E extends Exception> {
void accept(T t) throws E;
}
public static <T> Consumer<T> throwing(
ThrowingConsumer<T, Exception> throwingConsumer) {
return i -> {
try {
throwingConsumer.accept(i);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
};
}
@FunctionalInterface
public interface ThrowingReturnFunction<T, R, E extends Exception>{
R apply(T t) throws E;
}
public static <T, R> Function<T, R> throwReturn(
ThrowingReturnFunction<T, R, Exception> throwingFunction) {
return i -> {
try {
return throwingFunction.apply(i);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
};
}