5

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.

3
  • What else would you like to use it for - all Numbers? Commented May 22, 2015 at 18:09
  • @ChiefTwoPencils Yes you are right i just missed the obvious there, i edited it, the question is still valid for any number of lists, thanks Commented May 22, 2015 at 18:18
  • @sodik i mean for any number of lists, if i have lets say 100 lists, using index from a range and get their values 100 times seems overkilling. Commented May 22, 2015 at 18:21

1 Answer 1

5

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();
Sign up to request clarification or add additional context in comments.

2 Comments

small typo, it should be lists.stream().mapToInt(...), :-) Also couldn't you make this more performant with a .distinct().limit(2), so that as soon as you find more than 2 different sizes you stop the computations?
@user2336315 Fixed typo. Your suggestion of "limit" is OK, but frankly I wouldn't bother; the extra "cost" only shows up right before you are going to throw an exception anyway. Small optimizations on the will-fail paths are rarely worth the additional complexity.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.