How can I make Cartesian product with Java 8 streams?

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

    In loop create combined list

    List cartesianProduct(List> wordLists) {
    
     List cp = wordLists.get(0);
    
     for (int i = 1; i < wordLists.size(); i++) 
     {      
         List secondList = wordLists.get(i);
         List combinedList = cp.stream().flatMap(s1 -> secondList.stream().map(s2 -> s1 + s2))
                        .collect(Collectors.toList());
            cp = combinedList;
    
        }
            return cp;
    }
    

提交回复
热议问题