How can I make Cartesian product with Java 8 streams?

后端 未结 9 757
谎友^
谎友^ 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:33

    Cartesian product in Java 8 with forEach:

    List listA = new ArrayList<>();
    listA.add("0");
    listA.add("1");
    List listB = new ArrayList<>();
    listB.add("a");
    listB.add("b"); 
    
    List cartesianProduct = new ArrayList<>();
    listA.forEach(a -> listB.forEach(b -> cartesianProduct.add(a + b)));
    
    cartesianProduct.forEach(System.out::println);
    //Output : 0a 0b 1a 1b 
    

提交回复
热议问题