
Java 8:Lambda 流,透過異常處理方法進行過濾
在Java 8 中,流中的lambda 表達式可以有效地過濾元素。但是,在處理拋出 IOException 等已檢查異常的方法時,可能會出現複雜情況。
以下程式碼片段示範了此問題:
1 2 3 4 5 6 7 8 9 10 11 12 | <code class = "java" > class Bank {
public Set<String> getActiveAccountNumbers() throws IOException {
Stream<Account> s = accounts.values().stream();
s = s.filter(a -> a.isActive());
Stream<String> ss = s.map(a -> a.getNumber());
return ss.collect(Collectors.toSet());
}
}
interface Account {
boolean isActive() throws IOException;
String getNumber() throws IOException;
}</code>
|
登入後複製
此程式碼無法編譯,因為它無法處理lambda 表達式中的 isActive 和 getNumber 方法拋出 IOException。
要解決此問題,我們需要在異常轉義lambda 之前捕獲該異常:
1 2 3 4 5 6 7 | <code class = "java" >s = s.filter(a -> {
try {
return a.isActive();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
});</code>
|
登入後複製
當lambda 被評估時在未聲明受檢異常的不同上下文中,我們將受檢異常包裝在未檢測異常。
或者,您可以使用一種方法來消除編譯器的異常檢查:
1 2 3 | <code class = "java" > return s.filter(a -> uncheckCall(a::isActive))
.map(Account::getNumber)
.collect(toSet());</code>
|
登入後複製
其中uncheckCall 定義為:
1 2 3 4 5 6 7 8 | <code class = "java" > public static <T> T uncheckCall(Callable<T> callable) {
try {
return callable.call();
} catch (Exception e) {
sneakyThrow(e);
return null;
}
}</code>
|
登入後複製
此方法有效地將已檢查的異常轉換為未檢查的異常。但是,應謹慎使用,因為如果處理不當,可能會導致意外行為。
以上是在 Java 8 中將 Lambda 表達式與流結合使用時如何處理檢查異常?的詳細內容。更多資訊請關注PHP中文網其他相關文章!