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); }
source share