Java 如何使用流对 Map 中的值求和?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30089469/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to sum values in a Map with a stream?
提问by Jay
I want the equivalent of this with a stream:
我想要一个流的等价物:
public static <T extends Number> T getSum(final Map<String, T> data) {
T sum = 0;
for (String key: data.keySet())
sum += data.get(key);
return sum;
}
This code doesn't actually compile because 0 cannot be assigned to type T, but you get the idea.
这段代码实际上并没有编译,因为 0 不能分配给类型 T,但你明白了。
采纳答案by Radiodef
Here's another way to do this:
这是执行此操作的另一种方法:
int sum = data.values().stream().reduce(0, Integer::sum);
(For a sum to just int
, however, Paul's answer does less boxing and unboxing.)
(int
然而,对于一个总和,保罗的回答没有装箱和拆箱。)
As for doing this generically, I don't think there's a way that's much more convenient.
至于一般地这样做,我认为没有更方便的方法。
We could do something like this:
我们可以这样做:
static <T> T sum(Map<?, T> m, BinaryOperator<T> summer) {
return m.values().stream().reduce(summer).get();
}
int sum = MyMath.sum(data, Integer::sum);
But you always end up passing the summer. reduce
is also problematic because it returns Optional
. The above sum
method throws an exception for an empty map, but an empty sum should be 0. Of course, we could pass the 0 too:
但你总是以夏天过去告终。reduce
也有问题,因为它返回Optional
. 上面的sum
方法对空映射抛出异常,但空和应该是0。当然,我们也可以传递0:
static <T> T sum(Map<?, T> m, T identity, BinaryOperator<T> summer) {
return m.values().stream().reduce(identity, summer);
}
int sum = MyMath.sum(data, 0, Integer::sum);
回答by Paul Boddington
You can do this:
你可以这样做:
int sum = data.values().stream().mapToInt(Integer::parseInt).sum();
回答by Saeed Zarinfam
You can do it like this:
你可以这样做:
int creditAmountSum = result.stream().map(e -> e.getCreditAmount()).reduce(0, (x, y) -> x + y);