I have the following collection type:
Map> map;
I would like to create unique combinations of each o
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!