3 回答
TA貢獻1848條經(jīng)驗 獲得超2個贊
首先,您使用的是返回由指定數(shù)組支持的固定大小的列表,我認(rèn)為固定大小應(yīng)該告訴您做錯了什么。Arrays::asList
比你正在使用一個反模式來創(chuàng)建一個到位 - 通過創(chuàng)建一個匿名的內(nèi)部類,該類通過該.HashMapHashMapMap<String,List<Integer>> mapLstInteger=new HashMap<String,List<Integer>>()....
比,你違反了 的規(guī)范,它應(yīng)該一直返回一個新的對象,但你總是把 放入 。reduceoutputLst
比,你正在創(chuàng)造一個當(dāng)你所關(guān)心的只是它的價值 - 在這種情況下創(chuàng)建一個。MapList<List<Integer>>
根據(jù)你的代碼,即使是我在代碼下面寫的句子,對每個鍵執(zhí)行arrayList元素的總和也是不正確的。我會在我想要實現(xiàn)的實際事情上下定決心,然后如果我是你,我會嘗試去做。
TA貢獻2011條經(jīng)驗 獲得超2個贊
發(fā)生這種情況是因為您正在使用 由 生成的原始版本。
該抽象實現(xiàn)不允許添加或刪除元素。AbstractListArrays.asListList<T>
public void add(int index, E element) {
throw new UnsupportedOperationException();
}
但無論如何,回到你的問題。您也可以通過 自定義 獲得所需的內(nèi)容,您可以在其中提供自定義實現(xiàn),無論是 、 還是 其他任何您認(rèn)為更好的實現(xiàn)。CollectorList<T>ArrayListLinkedList
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貢獻1880條經(jīng)驗 獲得超4個贊
您應(yīng)該執(zhí)行以下操作:
mapLstInteger.values().stream() .flatMapToInt(list -> list.stream() .filter(Objects::nonNull) .mapToInt(Integer::intValue)).sum();
添加了篩選器,以確保在空整數(shù)的情況下不會獲得空指針。作為一般規(guī)則,如果您被迫在流中使用常規(guī)循環(huán),則可能做錯了什么。通過將 int 列表轉(zhuǎn)換為 int 值,我們可以很容易地求和,如您上所示。
最初誤解了問題,認(rèn)為你想要的總體總和,唉,這是實際問題的更新解決方案:
mapLstInteger.values().stream() .map(list -> list.stream() .filter(Objects::nonNull) .mapToInt(Integer::intValue).sum()) .collect(Collectors.toList());
添加回答
舉報
