Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 745
dotmindlabs Avatar asked May 22 '15 18:05

dotmindlabs


1 Answers

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();
like image 158
Brian Goetz Avatar answered Sep 28 '22 04:09

Brian Goetz