What accumulates the Java equivalent of C ++ or Groovy?

Essentially, I would like to do the following as a single line:

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

I see that there is http://functionaljava.org/examples/1.5/#Array.foldLeft , but I do not need to copy the collection.

+4
source share
3 answers

I see that there is http://functionaljava.org/examples/1.5/#Array.foldLeft , but I do not need to copy the collection.

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

+3
source

Sorry, it still does not exist in Java 7. You will have to wait for Java 8, where Closures should be implemented.

At the same time, you can use FunctionalJava, Guava, or a JVM-compatible language with closing enabled, such as Groovy.

0
source

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

 return fold(collectionOfInts, 0, ADD); 

Oh, and 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); } 
0
source

Source: https://habr.com/ru/post/1386198/


All Articles