【发布时间】:2015-11-18 09:41:07
【问题描述】:
据我所知,如果 lambda 实现的抽象方法的签名中没有 throws,则无法处理 lambda 中引发的异常。
我遇到了以下代码,它可以工作。为什么openStream() 不需要处理IOException?我可以在tryWithResources 中看到try-catch,但我不明白它背后的机制。
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.function.Function;
import java.util.function.Supplier;
public class Main {
public static <AUTOCLOSEABLE extends AutoCloseable, OUTPUT> Supplier<OUTPUT> tryWithResources(
Callable<AUTOCLOSEABLE> callable, Function<AUTOCLOSEABLE, Supplier<OUTPUT>> function,
Supplier<OUTPUT> defaultSupplier) {
return () -> {
try (AUTOCLOSEABLE autoCloseable = callable.call()) {
return function.apply(autoCloseable).get();
} catch (Throwable throwable) {
return defaultSupplier.get();
}
};
}
public static <INPUT, OUTPUT> Function<INPUT, OUTPUT> function(Supplier<OUTPUT> supplier) {
return i -> supplier.get();
}
public static void main(String... args) {
Map<String, Collection<String>> anagrams = new ConcurrentSkipListMap<>();
int count = tryWithResources(
() -> new BufferedReader(new InputStreamReader(
new URL("http://www.puzzlers.org/pub/wordlists/unixdict.txt").openStream())),
reader -> () -> reader.lines().parallel().mapToInt(word -> {
char[] chars = word.toCharArray();
Arrays.parallelSort(chars);
String key = Arrays.toString(chars);
Collection<String> collection = anagrams.computeIfAbsent(key, function(ArrayList::new));
collection.add(word);
return collection.size();
}).max().orElse(0), () -> 0).get();
anagrams.values().stream().filter(ana -> ana.size() >= count).forEach((list) -> {
for (String s : list)
System.out.print(s + " ");
System.out.println();
});
}
}
【问题讨论】:
标签: java lambda exception-handling java-8