简体   繁体   中英

What's the Java equivalent of C++'s accumulate or Groovy's inject?

Essentially, I'd like to do the following as a one-liner:

        int sum = initialValue;
        for (int n : collectionOfInts) {
            sum += n;
        }
        return sum;

I see that there's http://functionaljava.org/examples/1.5/#Array.foldLeft , but I'd rather not have to copy the collection.

I see that there's http://functionaljava.org/examples/1.5/#Array.foldLeft , but I'd rather not have to copy the collection.

If you use the foldLeft from IterableW instead of Array, you won't have to copy anything.

Sorry, it still doesn't exist in Java 7. You'll have to wait for Java 8, where Closures shall be implemented.

In the meantime, you can use FunctionalJava, Guava, or a JVM-compatible, closure-enabled language such as Groovy.

Just for fun - here's how to do it without an external library:

return fold(collectionOfInts, 0, ADD);

Oh, and here's the rest :)

static <X, Y> X fold(final Iterable<? extends Y> gen, final X initial, final Function2<? super X, ? super Y, ? extends X> function) {
  final Iterator<? extends Y> it = gen.iterator();
  if (!it.hasNext()) {
    return initial;
  }
  X acc = initial;
  while (it.hasNext()) {
    acc = function.apply(acc, it.next());
  }
  return acc;
}

static final Function2<Integer, Integer, Integer> ADD = new Function2<Integer, Integer, Integer>() {
  @Override
  public Integer apply(Integer a, Integer b) {
    return a + b;
  }
};

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM