How can I make Cartesian product with Java 8 streams?

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

    A solution that mainly operates on lists, making things a lot simpler. It does a recursive call in flatMap, keeping track of the elements that have already been combined, and the collections of elements that are still missing, and offers the results of this nested recursive construction as a stream of lists:

    import java.util.*;
    import java.util.stream.Stream;
    
    public class CartesianProduct {
    
        public static void main(String[] args) {
            Map> map = 
                new LinkedHashMap>();
            map.put("A", Arrays.asList("a1", "a2", "a3", "a4"));
            map.put("B", Arrays.asList("b1", "b2", "b3"));
            map.put("C", Arrays.asList("c1", "c2"));
            ofCombinations(map.values()).forEach(System.out::println);
        }
    
        public static  Stream> ofCombinations(
            Collection> collections) {
            return ofCombinations(
                new ArrayList>(collections), 
                Collections.emptyList());        
        }       
    
        private static  Stream> ofCombinations(
            List> collections, List current) {
            return collections.isEmpty() ? Stream.of(current) :
                collections.get(0).stream().flatMap(e -> 
                {
                    List list = new ArrayList(current);
                    list.add(e);
                    return ofCombinations(
                        collections.subList(1, collections.size()), list);
                });
        }
    }
    

提交回复
热议问题