3 回答

TA贡献1779条经验 获得超6个赞
首先,您使用Arrays::asList
的是记录为返回由指定数组支持的固定大小列表,我认为固定大小应该告诉您您做错了什么。
HashMap
比您使用创建就地的反模式- 通过创建扩展的匿名内部类HashMap
,通过 that Map<String,List<Integer>> mapLstInteger=new HashMap<String,List<Integer>>()....
。
比,你违反了 的规范reduce
,它应该一直返回一个新的对象,但你总是放入outputLst
.
比,Map
当你只关心它的值时,你正在创建一个 -List<List<Integer>>
在这种情况下创建一个。
根据您的代码,即使您在代码下面编写的用于针对每个键对 arrayList 元素求和的句子也不正确。如果我是你,我会在我想要实现的实际目标上下定决心,然后尝试去做。

TA贡献1785条经验 获得超8个赞
发生这种情况是因为您使用的AbstractList是由Arrays.asList.
该List<T>抽象实现不允许添加或删除元素。
public void add(int index, E element) {
throw new UnsupportedOperationException();
}
但无论如何,回到你的问题。您也可以通过 custom获得您想要的东西Collector,您可以在其中提供您的自定义List<T>实现,无论是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条经验 获得超22个赞
您应该执行以下操作:
mapLstInteger.values().stream() .flatMapToInt(list -> list.stream() .filter(Objects::nonNull) .mapToInt(Integer::intValue)).sum();
添加了过滤器以确保在空整数的情况下不会获得空指针。作为一般规则,如果您被迫在流中使用常规循环,您可能做错了什么。通过将 int 列表更改为 int 值,我们可以轻松地求和,如上所示。
最初误解了这个问题,认为您想要总和,唉,这是针对实际问题的更新解决方案:
mapLstInteger.values().stream() .map(list -> list.stream() .filter(Objects::nonNull) .mapToInt(Integer::intValue).sum()) .collect(Collectors.toList());
添加回答
举报