3 回答

TA貢獻1779條經(jīng)驗 獲得超6個贊
首先,您使用Arrays::asList
的是記錄為返回由指定數(shù)組支持的固定大小列表,我認為固定大小應(yīng)該告訴您您做錯了什么。
HashMap
比您使用創(chuàng)建就地的反模式- 通過創(chuàng)建擴展的匿名內(nèi)部類HashMap
,通過 that Map<String,List<Integer>> mapLstInteger=new HashMap<String,List<Integer>>()....
。
比,你違反了 的規(guī)范reduce
,它應(yīng)該一直返回一個新的對象,但你總是放入outputLst
.
比,Map
當你只關(guān)心它的值時,你正在創(chuàng)建一個 -List<List<Integer>>
在這種情況下創(chuàng)建一個。
根據(jù)您的代碼,即使您在代碼下面編寫的用于針對每個鍵對 arrayList 元素求和的句子也不正確。如果我是你,我會在我想要實現(xiàn)的實際目標上下定決心,然后嘗試去做。

TA貢獻1785條經(jīng)驗 獲得超8個贊
發(fā)生這種情況是因為您使用的AbstractList是由Arrays.asList.
該List<T>抽象實現(xiàn)不允許添加或刪除元素。
public void add(int index, E element) {
throw new UnsupportedOperationException();
}
但無論如何,回到你的問題。您也可以通過 custom獲得您想要的東西Collector,您可以在其中提供您的自定義List<T>實現(xiàn),無論是ArrayList,LinkedList還是您覺得更好的任何東西。
mapLstInteger.values()
.stream()
.collect(Collector.of(
() -> new ArrayList<>(), // Supplier
(output, toSumList) -> { // Accumulator
output.add(toSumList.stream()
.mapToInt(Integer::intValue)
.sum());
},
// The Combiner implementation will be called
// in case of a "parallel" Stream.
// No need to worry about it here.
// But in case, we would need to merge the partial results
(output, partial) -> {
output.addAll(partial);
return output;
}
));
更簡潔的版本是
mapLstInteger.values()
.stream()
.map(l -> l.stream().mapToInt(Integer::intValue).sum())
.collect(Collectors.toCollection(ArrayList::new));
這將正確輸出[6, 15, 24]

TA貢獻1842條經(jīng)驗 獲得超21個贊
您應(yīng)該執(zhí)行以下操作:
mapLstInteger.values().stream() .flatMapToInt(list -> list.stream() .filter(Objects::nonNull) .mapToInt(Integer::intValue)).sum();
添加了過濾器以確保在空整數(shù)的情況下不會獲得空指針。作為一般規(guī)則,如果您被迫在流中使用常規(guī)循環(huán),您可能做錯了什么。通過將 int 列表更改為 int 值,我們可以輕松地求和,如上所示。
最初誤解了這個問題,認為您想要總和,唉,這是針對實際問題的更新解決方案:
mapLstInteger.values().stream() .map(list -> list.stream() .filter(Objects::nonNull) .mapToInt(Integer::intValue).sum()) .collect(Collectors.toList());
添加回答
舉報