How can I make Cartesian product with Java 8 streams?

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

    Here is another solution, which does not use as many features from Streams as Tagir's example; however I believe it to be more straight-forward:

    public class Permutations {
    
        transient List> perms;
    
        public List> list(Map> map) {
    
            SortedMap> sortedMap = new TreeMap<>();
            sortedMap.putAll(map);
    
            sortedMap.values().forEach((v) ->  perms = expand(perms, v));
    
            return perms;
        }
    
        private List> expand(List> list, Collection elements) {
    
            List> newList = new LinkedList<>();
    
            if (list == null) {
                elements.forEach((e) -> {
                    SortedSet set = new TreeSet<>();
                    set.add(e);
                    newList.add(set);
                });
            } else {
                list.forEach((set) ->
                    elements.forEach((e) -> {
                        SortedSet newSet = new TreeSet<>();
                        newSet.addAll(set);
                        newSet.add(e);
                        newList.add(newSet);
                    }));
            }
    
            return newList;
        }
    }
    

    You can remove the Sorted prefix if you are not interested in ordering of elements; though, I think it's easier to debug if everything is sorted.

    Usage:

    Permutations p = new Permutations();
    List> plist = p.list(map);
    plist.forEach((s) -> System.out.println(s));
    

    Enjoy!

提交回复
热议问题