dotmindlabs
dotmindlabs

Reputation: 908

Java Streams API summing Lists at index

i would like to know if there is a more efficient way to sum all tree lists - summing their values at the same index.

The reason why i am asking its because, probably using Streams API, its possible to make it more generic, for any number of lists.

List<Double> listA = getListA();
List<Double> listB = getListB();
List<Double> listC = getListC();

int listsSize = listA.size();

    List<?> collect = IntStream.range(0, listsSize)
            .mapToObj(i -> listA.get(i) + listB.get(i) + list(C).get(i))
            .collect(toList());

thanks for any insight.

Upvotes: 5

Views: 1323

Answers (1)

Brian Goetz
Brian Goetz

Reputation: 95554

How about this:

List<List<Double>> lists = ...;

// ensure all lists are same size, and get size
int[] sizes = lists.stream().mapToInt(List::size).distinct().toArray();
if (sizes.length != 1)
    throw ...
int size = sizes[0];

double[] sums =
    IntStream.range(0, size)
             .mapToDouble(i -> lists.stream().mapToDouble(list -> list.get(i)).sum())
             .toArray();

Upvotes: 5

Related Questions