How can I make Cartesian product with Java 8 streams?

后端 未结 9 773
谎友^
谎友^ 2020-11-28 08:10

I have the following collection type:

Map> map;

I would like to create unique combinations of each o

9条回答
  •  情书的邮戳
    2020-11-28 08:50

    A simpler answer, for a simpler situation where you just want to have the cartesian product of the elements of two collections.

    Here's some code which uses flatMap to generate the cartesian product of two short lists:

        public static void main(String[] args) {
          List aList = Arrays.asList(1,2,3);
          List bList = Arrays.asList(4,5,6);
    
          Stream> product = aList.stream().flatMap(a -> 
              bList.stream().flatMap(b ->
                Stream.of(Arrays.asList(a, b)))
              );
    
          product.forEach(p -> { System.out.println(p); });
    
    // prints:
    //              [1, 4]
    //              [1, 5]
    //              [1, 6]
    //              [2, 4]
    //              [2, 5]
    //              [2, 6]
    //              [3, 4]
    //              [3, 5]
    //              [3, 6]
        }
    

    If you want to add more collections, just nest the streams a litter further:

            aList.stream().flatMap(a -> 
              bList.stream().flatMap(b ->
                cList.stream().flatMap(c ->
                   Stream.of(Arrays.asList(a, b, c))))
              );
    

提交回复
热议问题