How can I make Cartesian product with Java 8 streams?

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

    Use a Consumer Function Class, a List and a foreach

        public void tester(){
    
            String[] strs1 = {"2","4","9"};
            String[] strs2 = {"9","0","5"};
    
            //Final output is {"29", "49, 99", "20", "40", "90", "25", "45", "95"}
            List<String> result = new ArrayList<>();
            Consumer<String> consumer = (String str) -> result.addAll(Arrays.stream(strs1).map(s -> s+str).collect(Collectors.toList()));
            Arrays.stream(strs2).forEach(consumer);
    
            System.out.println(result);
    
    }
    
    0 讨论(0)
  • 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<Integer> aList = Arrays.asList(1,2,3);
          List<Integer> bList = Arrays.asList(4,5,6);
    
          Stream<List<Integer>> 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))))
              );
    
    0 讨论(0)
  • 2020-11-28 08:52

    While it's not a Stream solution, Guava's com.google.common.collect.Sets does that for you

    Set<List<String>> result = Sets.cartesianProduct(Set.of("a1","a2"), Set.of("b1","b2"), Set.of("c1","c2" ))
    
    0 讨论(0)
提交回复
热议问题