在輸入中,我有一個整數和字串串列。
第一個流作業正常,第二個流作業直到過濾器,我不知道為什么。我的代碼:
import java.util.List;
import java.util.stream.*;
public class MixedSum {
public int sum(List<?> mixed) {
int m = mixed.stream().filter(x -> x instanceof String).map(x -> Integer.parseInt((String) x)).collect(Collectors.summingInt(Integer::intValue));
int n = mixed.stream().filter(x -> x instanceof Integer).collect(Collectors.summingInt(Integer::intValue));
return m n;
}
}
我有這個錯誤:
錯誤:沒有找到適合 collect(Collector<Integer,CAP#1,Integer>) int n = mixed.stream().filter(x -> x instanceof Integer).collect(Collectors.summingInt(Integer::intValue) 的方法); ^ 方法 Stream.<R#1>collect(Supplier<R#1>,BiConsumer<R#1,? super CAP#2>,BiConsumer<R#1,R#1>) 不適用(無法推斷型別-變數 R#1(實際引數串列和形式引數串列的長度不同))方法 Stream.<R#2,A>collect(Collector<? super CAP#2,A,R#2>) 不適用(推斷型別不符合推斷的上限:CAP#2 上限:Integer,Object) 其中 R#1,T,R#2,A 是型別變數:R#1 擴展方法中宣告的物件<R#1>collect(供應商<R#1>,BiConsumer<R#1,? super T>,BiConsumer<R#1,R#1> ) T 擴展介面 Stream R#2 中宣告的物件 擴展方法 <R#2,A>collect(Collector<? super T,A,R#2>) 中宣告的物件 A 擴展方法 <R#2,A 中宣告的物件>collect(Collector<? super T,A,R#2>) 其中 CAP#1,CAP#2 是新的型別變數:CAP#1 從 ? CAP#2 從 ? 1 個錯誤
uj5u.com熱心網友回復:
在第二個流中應用方法參考之前Integer::intValue,您必須將流的元素轉換為Integer型別。
由于您只想獲得整數基元的總和,因此無需求助于收集器,相反,您可以強制物件流IntStream并應用該sum()方法。
int m = mixed.stream()
.filter(x -> x instanceof String)
.mapToInt(x -> Integer.parseInt((String) x))
.sum();
int n = mixed.stream()
.filter(x -> x instanceof Integer)
.mapToInt(x -> (Integer) x)
.sum();
無需進行兩次迭代,因為在源串列中,您只能丟棄Integer和型別過濾器。String所以你的方法最終歸結為幾行:
public int sum(List<?> mixed) {
return mixed.stream()
.mapToInt(x -> x instanceof Integer? (Integer) x : Integer.parseInt((String) x))
.sum();
}
筆記:
- 因為如果轉換失敗,如果源串列包含至少一個字串,該字串由數字以外的其他符號組成,則
Integer.parseInt()可能會導致流將不會生成該值。這就是所謂的快速失敗實作,如果您的意圖不是在無效資料的情況下回傳值而是用例外強調它,那么它是有意義的。NumberFormatException - 值得指出的另一件事是,此代碼僅作為練習具有價值。在某些語言
String | Number中instanceof,您可能會遇到聯合型別(它可能是使用行型別集合或類作為泛型型別來完成的,以繞過編譯器。相反,像這樣單獨處理字串值的來源會更干凈,更不容易出錯:Object
strSource.stream().map(Integer::parseInt).collect(Collectors.toList());
因此,sum()方法將免除多余的責任和合同:
list.stream().mapToInt(Integer::intValue).sum();
uj5u.com熱心網友回復:
編譯器無法推斷型別。您需要像在第一步中那樣進行投射:
int n = mixed.stream()
.filter(x -> x instanceof Integer)
.map(x -> (int) x)
.collect(Collectors.summingInt(Integer::intValue));
或者如果你想使用方法參考
int n = mixed.stream()
.filter(x -> x instanceof Integer)
.map(Integer.class::cast)
.collect(Collectors.summingInt(Integer::intValue));
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/430306.html
上一篇:平均多個串列的每個第n個元素
下一篇:在資料框中的串列物件中查找值
