我有一个 HashMap<GC,List<RR>>
,其示例数据如下:
key values
gc1 - rr1
- rr2
- rr3
gc2 - rr4
- rr5
gc3 - rr6
我需要根据不同的GC,创建出所有可能的RR组合,例如:
Combination1: rr1, rr4, rr6
Combination2: rr1, rr5, rr6
Combination3: rr2, rr4, rr6
Combination4: rr2, rr5, rr6
Combination5: rr3, rr4, rr6
Combination6: rr3, rr5, rr6
到目前为止,我尝试的方法是按照 @Sanket Makani 的建议,将我的
HashMap<GC, List<RR>>
转换为 List<List<RR>>
,然后像这样遍历所有元素:List<List<RR>> inputList = new ArrayList<List<RR>>();
for (Map.Entry<GC, List<RR>> rrList : Map.entrySet()) {
inputList.add(rrList.getValue());
}
List<List<RR>> combinationsList = new ArrayList<List<RR>>();
for (List<RR> rrList : inputList) {
List<RR> rrList1 = new ArrayList<RR>();
for (RR rr : rrList) {
rrList1.add(rr);
}
combinationsList.add(rrList1);
}
这对我来说并不起作用,因为它会将所有的 RR 分组到一个 GC 中,如下:
Combination1: rr1, rr2, rr3
Combination2: rr4, rr5
Combination3: rr6
所以我的问题是,我该如何调整我的代码以获得期望的结果?
PS:不幸的是,我正在使用Java6,因此不允许使用Lambda/Stream。
PS2:我看到了类似的问题,但找不到我要找的确切示例。
编辑:
这是我根据@nandsito的答案最终实现的代码:
//this method groups RRs by GC key with a given list
HashMap<GC, List<RR>> GCRRHashMap = groupRRsByGC(list);
List<Map.Entry<GC, List<RR>>> mapEntryList = new ArrayList<Map.Entry<GC, List<RR>>>(GCRRHashMap.entrySet());
List<List<RR>> combinationsList = new ArrayList<List<RR>>();
List<RR> combinations = new ArrayList<RR>();
generateCombinations(mapEntryList, combinations, combinationsList);
private void generateCombinations(
List<Map.Entry<GC, List<RR>>> mapEntryList,
List<RR> combinations, List<List<RR>> combinationsList) {
if (mapEntryList.isEmpty()) {
combinationsList.add(new ArrayList<RoomStay>(combinations));
return;
}
Map.Entry<GC, List<RR>> entry = mapEntryList.remove(0);
List<RR> entryValue = new ArrayList<RR>(entry.getValue());
while (!entryValue.isEmpty()) {
RR rr = entryValue.remove(0);
combinations.add(rr);
generateCombinations(mapEntryList, combinations, combinationsList);
combinations.remove(combinations.size() - 1);
}
mapEntryList.add(0, entry);
}
List<List<RR>>
中,然后编写一个递归算法来打印所有的组合。或者你可以将所有的组合存储在ArrayList<StringBuilder>
中,然后进行打印。 - Sanket Makani