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);
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())
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())
map() will return another
mapToObj() will return a