I’m stuck with a simple task. What I want to do is to transform Map<K,Set<V>> into the List<Map<K,V>> getting all possible combinations:
Map {
{'k1' => set{'v11', 'v12'}},
{'k2' => set{'v21', 'v22', 'v23'}},
{'k3' => set{'v31'}}
}
Expected result:
List
{
Map{'k1'=>'v11', 'k2'=>'v21', 'k3'=>'v31'},
Map{'k1'=>'v11', 'k2'=>'v22', 'k3'=>'v31'},
Map{'k1'=>'v11', 'k2'=>'v23', 'k3'=>'v31'},
Map{'k1'=>'v12', 'k2'=>'v21', 'k3'=>'v31'},
Map{'k1'=>'v12', 'k2'=>'v22', 'k3'=>'v31'},
Map{'k1'=>'v12', 'k2'=>'v23', 'k3'=>'v31'}
}
Use recursion! So at each level of the recursion, you look at another key in the
keyset()of the map. You add iteratively add elements in theSet<V>for that key to the current map that you want to add to the list.You can think of this as a tree. At the root node, you have an empty list. Then each subsequent level of the tree
irepresents a choice of which element to take from theith set.Here is the code along with a main method containing a test case: