How to Stream Two Lists at Once in Java

Published Jul 11, 2022

How can we stream through multiple lists simultaneously in Java?

Suppose we want to stream through the following lists and add the elements from each list at the same indices.

List<Integer> list1 = Arrays.asList(1, 2, 3);
List<Integer> list2 = Arrays.asList(2, 3, 4);

1. Using (Guava)

We can use Guava’s to zip through two lists. For the third parameter, we’ll want to pass in the function to execute on the current element from each list.

List<Integer> res = Streams
    (a, b) -> a + b

2. Using IntStream.range()

We can also use IntStream.range() similar to how we would use an index in a traditional loop.

List<Integer> list = IntStream.range(0, list1.size())
  .mapToObj(i -> list1.get(i) + list2.get(i))

With IntStream, using map() will return another IntStream while mapToObj() will return a Stream<T>