Question:
There are 2 collections: c1 = Arrays.asList("A", "B", "C")
and c2 = Arrays.asList("1", "2", "3")
. Tell me how to make a collection {"A1", "B2", "C3"}
using the Stream API in Java in 1 line?
Answer:
For some reason, there is no zip
operation in standard streams, so you have to resort to debauchery like
IntStream
.range(0, Math.min(c1.size(), c2.size()))
.mapToObj(i -> c1.get(i) + c2.get(i))
.forEach(System.out::println);
But zip
is in Guava
Streams
.zip(c1.stream(), c2.stream(), (x, y) -> x + y)
.forEach(System.out::println);
And in StreamEx
StreamEx.of(c1)
.zipWith(StreamEx.of(c2), (x, y) -> x + y)
.forEach(System.out::println);