本文介绍了如何使用流对 Map 中的值求和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个流的等价物:

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;
}

这段代码实际上无法编译,因为 0 不能分配给类型 T,但您明白了.

This code doesn't actually compile because 0 cannot be assigned to type T, but you get the idea.

推荐答案

这是另一种方法:

int sum = data.values().stream().reduce(0, Integer::sum);

(但是,对于 int 的总和,Paul 的回答减少了装箱和拆箱.)

(For a sum to just int, however, Paul's answer does less boxing and unboxing.)

至于一般地,我认为没有比这更方便的方法了.

As for doing this generically, I don't think there's a way that's much more convenient.

我们可以这样做:

static <T> T sum(Map<?, T> m, BinaryOperator<T> summer) {
    return m.values().stream().reduce(summer).get();
}

int sum = MyMath.sum(data, Integer::sum);

但你总是以夏天结束.reduce 也有问题,因为它返回 Optional.上面的sum方法会抛出一个空map的异常,但是空的sum应该是0,当然我们也可以传0:

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:

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);

这篇关于如何使用流对 Map 中的值求和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 18:16