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);
}
Last update: 2020-05-25. The Java Iterable interface represents a collection of objects which is iterable - meaning which can be iterated. This means, that a class that implements the Java Iterable interface can have its elements iterated.
IntStream's sum() method A simple solution to calculate the sum of all elements in a List is to convert it into IntStream and call sum() to get the sum of elements in the stream. There are several ways to get IntStream from Stream<Integer> using mapToInt() method.
Since Java 8 is now out getting a sum on collections is simple:
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()
Functional Java has a sum method:
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With