java Java中的可迭代总和?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4758341/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 07:53:32  来源:igfitidea点击:

Iterable Sum in Java?

java

提问by ripper234

Is there a library that does this:

有没有这样做的图书馆:

public class Iterables{
    private Iterables() {}

    public static <T> int sum(Iterable<T> iterable, Func<T, Integer> func) {
        int result = 0;
        for (T item : iterable)
            result += func.run(item);
        return result;
    }
}

public interface Func<TInput, TOutput> {
    TOutput run(TInput input);
}

回答by Henrik Gustafsson

There are basically two useful libraries that can help with this; Google Guavaand Apache Commons Collections.

基本上有两个有用的库可以帮助解决这个问题;Google GuavaApache Commons Collections

What you are trying to do is basically two operations, first mapping, then reduction. I've never used Commons Collections to any extent myself so I can't tell you more about that, but I know there is no support for reduction (or folding) in Google Guava at least (see Issue 218). This is not too hard to add yourself though (not tested):

您要做的基本上是两个操作,首先是映射,然后是归约。我自己从未在任何程度上使用过 Commons Collections,所以我不能告诉你更多关于它的信息,但我知道至少在 Google Guava 中不支持减少(或折叠)(参见第 218 期)。尽管添加自己并不太难(未测试):

interface Function2<A, B> {
  B apply(B b, A a);
}

public class Iterables2 {
    public static <A, B> B reduce(Iterable<A> iterable,
      B initial, Function2<A, B> fun) {
        B b = initial;
        for (A item : iterable)
             b = fun.apply(b, item);
        return b;
    }
}

That way you can combine it with Guavas Iterables.transform() like so:

这样你就可以像这样将它与 Guavas Iterables.transform() 结合起来:

class Summer implements Function2<Integer, Integer> {
    Integer apply(Integer b, Integer a) {
        return b + a;
    }
}

class MyMapper<T> implements Function<T, Integer> {
    Integer apply(T t) {
      // Do stuff
    }
}

And then (provided you've import static'ed the relevant classes):

然后(假设您已导入静态相关类):

reduce(transform(iterable, new MyMapper()), 0, new Summer());

Also see this question.

另请参阅此问题

回答by Peter Lawrey

Java is not a functional langugae and often it simpler and faster to just using a plain loop.

Java 不是函数式语言,通常只使用普通循环更简单、更快。

You could write something like

你可以写类似的东西

List<String> list = /* ... */
int totalLength = Iterables.sum(list, new Func<String, Integer>() {
    public Integer run(String input) {
        return input.length();
    }
});

however IMHO its shorter and simpler to just write.

但是恕我直言,它的编写更短更简单。

List<String> list = /* ... */
int totalLength = 0;
for(String s: list) totalLength += s.length();

When closures become standard in Java, this will change but for now a loop is often the best way.

当闭包在 Java 中成为标准时,这将会改变,但现在循环通常是最好的方法。

回答by Andrejs

Since Java 8 is now out getting a sum on collections is simple:

由于 Java 8 现已发布,因此获取集合的总和很简单:

collection.stream().reduce(0, Integer::sum)

Unfortunately stream is not available on iterables but one can always convert. Arrays are easier:

不幸的是,流在可迭代对象上不可用,但始终可以转换。数组更简单:

LongStream.of(1, 2, 3).sum()

回答by eirirlar

Functional Java has a sum method:

函数式 Java 有一个 sum 方法:

http://functionaljava.googlecode.com/svn/artifacts/3.0/javadoc/fj/function/Integers.html#sum%28fj.data.List%29

http://functionaljava.googlecode.com/svn/artifacts/3.0/javadoc/fj/function/Integers.html#sum%28fj.data.List%29

Here's an example:

下面是一个例子:

List<Integer> ints = new ArrayList<Integer>();
ints.add(1);
ints.add(2);
ints.add(3);
int sum = Integers.sum(fj.data.List.iterableList(ints));

回答by Andrejs

You could simply use Lamdaj- a library to manipulate collections in a pseudo-functional and statically typed way:

您可以简单地使用Lamdaj- 一个以伪函数和静态类型方式操作集合的库:

sum = Lambda.sum(iterable);

It can also do other types of aggregation or you can addd you own Aggregators:

它还可以进行其他类型的聚合,或者您可以添加自己的聚合器:

sum = Lambda.aggregate(seq, new InitializedPairAggregator<Integer>(0) {
    protected Integer aggregate(Integer first, Integer second) {
        return first + second;
    }
});

See Featuresfor other examples.

有关其他示例,请参阅功能