Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterable Sum in Java?

Tags:

java

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);
}
like image 473
ripper234 Avatar asked Jan 21 '11 11:01

ripper234


People also ask

What is a Iterable in Java?

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.

How do you find the sum of a List in Java?

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.


2 Answers

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()
like image 172
Andrejs Avatar answered Oct 15 '22 03:10

Andrejs


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));
like image 23
eirirlar Avatar answered Oct 15 '22 02:10

eirirlar