我有一個精簡版的代碼來說明The method anyMatch(Predicate<? super capture#26-of ?>) in the type Stream<capture#26-of ?> is not applicable for the arguments (Predicate<Map<?,?>>)我遇到的問題:
private void func(Object o) {
Predicate<Map<?, ?>> pred = m -> true;
if (o instanceof Map && pred.test((Map<?, ?>) o)) {
// ...pred.test is OK
} else if (o instanceof Collection && ((Collection<?>) o).stream().filter(i -> i instanceof Map).anyMatch(pred)) {
// ...anyMatch here gives the above error
}
}
您將如何修復代碼以消除錯誤?謝謝!
uj5u.com熱心網友回復:
您已應用instanceofcheck in 的filter()事實不會改變流的型別,它仍然是Stream<Object>.
filter()操作是為了從流中丟棄元素,而不是修改元素,因此它不能改變流的型別。
要執行修改,您需要應用map()操作并通過型別轉換或方法使用轉換Class.cast():
.<Map<?,?>>map(Map.class::cast)
或者
.map(i -> (Map<?, ?>) i)
或者,您可以利用 Java 16模式匹配作為實體filter,并map在一個步驟中通過使用mapMulty()Java 16 中引入的方式將兩者結合起來:
((Collection<?>) o).stream()
.<Map<?,?>>mapMulti((i, consumer) -> {
if (i instanceof Map m) consumer.accept(m);
})
.anyMatch(pred)
uj5u.com熱心網友回復:
過濾后,Map您需要將其轉換為Map<?, ?>.
private void func(Object o) {
Predicate<Map<?, ?>> pred = m -> true;
if (o instanceof Map && pred.test((Map<?, ?>) o)) {
// ...pred.test is OK
} else if (o instanceof Collection && ((Collection<?>) o).stream()
.filter(i -> i instanceof Map).map(i -> (Map<?, ?>)i).anyMatch(pred)) {
// ...anyMatch here gives the above error
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/525397.html
標籤:爪哇仿制药java流谓词
下一篇:如何在java中修改最終地圖
