Java 8 – flatmap to find a pair of elements from two List

Today we will see how using java 8 stream flatmap method we can wind all the pairs from two Lists.

Let’s say we have the following lists [1,2,3], [4,5], after pairing we should have [{1,4}, {1,5}, {2,4}, {2,5}, {3,4}, {3,5}]. First thing that comes to mind is to use two map functions, iterate over two lists and make the pairs.

List list1 = Arrays.asList(1, 2, 3);
List list2 = Arrays.asList(3, 4);
List<Integer[]> pairs =
        list1.stream()
                .map(i -> list2.stream()
                        .map(j -> new Integer[]{i, j})
                ).
                collect(Collectors.toList());

But this solution will not work and the problem is that lambda passed to second map function will return Integer[]. So the stream returned by the map will be Stream<Integer[]>. And the first map itself will return Stream<Stream<Integer[]>>. But what we actually need is Stream<Integer[]>. This is where flatMap comes into play. It concatenates all the separate streams into a single stream: Stream<Integer[]>

List list1 = Arrays.asList(1, 2, 3);
List list2 = Arrays.asList(3, 4);
List<Integer[]> pairs =
        list1.stream()
                .flatMap(i -> list2.stream()
                        .map(j -> new Integer[]{i, j})
                ).
                collect(Collectors.toList());
pairs.forEach(pair -> System.out.println(pair[0] + " " + pair[1]));

//Output

1 3
1 4
2 3
2 4
3 3
3 4