Merging Streams in Java
I was asked in one of the interviews so I thought I would share this solution. Just could not remember how I used it in the past so revisited this. I thought this was a good use-case for flatmap. I guess the interviewer was after flatmap which I completely missed at the time :)
So the problem goes like this :-
If you had 2 streams
A, B, C
1,2,3
How would you merge the two so it becomes A1, B2, C3….
List<String> l1 = Arrays.asList("A", "B", "C");
List<String> l2 = Arrays.asList("1", "2", "3");
final Iterator<String> l2iterator = l2.iterator();
System.out.println(l1.stream()
.flatMap(
k -> l2iterator.hasNext()
? Stream.of(k + l2iterator.next()) : Stream.of(k)
).collect(Collectors.toList()));
This results in output
A1, B2, C3
Flatmap in this case flattens the output stream as a single stream which gets collected to a single stream of merged elements.
While we are at this the other question was how we join each element with all elements from another stream
List<String> l1 = Arrays.asList("A", "B", "C");
List<String> l2 = Arrays.asList("1", "2", "3");
System.out.println(
l1.stream()
.flatMap(k -> l2.stream().map(k2 -> k + k2))
.collect(Collectors.toList()));
A lot easier as you can see. All you are doing is iterating for each element of l2 over l1 and flatmap again comes to the rescue giving a single stream to collect or consume. :)
The output for the above of course is
[A1, A2, A3, B1, B2, B3, C1, C2, C3]
Although both solutions are valid they are limited in some ways. I will update more when I have solved this for infinite streams and of varying length where you want an outer join. The first solution is for a left-join on index.
The second one will not scale very well, but I think that is kind of expected. I would not use it on infinite streams (or large ones).
so here’s the main difference between map and flatmap. Map is supposed to return a transformed output for any input in the stream.
Flatmap flattens the input stream to 0 -> n elements. So for example we could have returned a stream with map method but that would have returned a stream of streams as opposed to still a stream of strings in case of a flatmap.