Search code examples
javajava-8java-streamcross-product

Cross product of two collections using the Stream API


I have two lists:

List<Integer> list1 = ...
List<Integer> list2 = ...

I have the following class:

class Pair {
    public Pair(final Integer i1, final Integer i2) {
        ...
    }
}

Is it possible with Java8 streams to combine the two input lists to a List<Pair>? This can be easily done with a double for-loop, but I am wondering if this is possible with Java8 streams.


Solution

  • list1.stream()
         .flatMap(i1 -> list2.stream()
                             .map(i2 -> new Pair(i1, i2)))
         .collect(Collectors.toList());