Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 579
Japser Jeper Avatar asked Sep 20 '25 06:09

Japser Jeper


1 Answers

list1.stream()
     .flatMap(i1 -> list2.stream()
                         .map(i2 -> new Pair(i1, i2)))
     .collect(Collectors.toList());
like image 96
JB Nizet Avatar answered Sep 22 '25 21:09

JB Nizet