How to Stream Two Lists at Once in Java


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 Streams.zip() (Guava)

We can use Guava’s Streams.zip() 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
  .zip(
    list1.stream(), 
    list2.stream(), 
    (a, b) -> a + b
  )
  .collect(Collectors.toList())

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))
  .collect(Collectors.toList())

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