我有一个包含可变长度字符串列表的映射。例如
Map<String, List<String> map = new HashMap<>();
map.put("key", "key1, key2);
map.put("name", "name1, name2, name3");
map.put("code", "code1, code2");
这将给出12个不同的排列。下面的代码可以完成这项工作
List<String> values = new ArrayList<>();
for (int i = 0; i < map.get("key").size(); i++) {
values.add(map.get("key").get(i));
for (int j = 0; j < map.get("name").size(); j++) {
values.add(map.get("name").get(j));
for (int k = 0; k < map.get("code").size(); k++) {
values.add(map.get("code").get(k));
}
}
}
预期输出:
"key1", "name1", "code1",
"key1", "name1", "code2",
"key1", "name2", "code1",
"key1", "name2", "code2",
"key1", "name3", "code1",
"key1", "name3", "code2",
"key2", "name1", "code1",
"key2", "name1", "code2",
"key2", "name2", "code1",
"key2", "name2", "code2",
"key2", "name3", "code1",
"key2", "name3", "code2"
但是问题是这是用3个for循环硬编码的,但是我希望可以支持任何数量的变量。及时的帮助深表感谢。
我使用递归在下面提供了示例解决方案。
在示例中,我们有3个列表,其中3、4、4个元素;程序将打印所有3 * 4 * 4 = 48个元素组合。
[从一个空组合(一个空列表)开始,在每个步骤(i)中,我们取N = list(i).size()个当前元组的副本,然后添加value(j)= list(i)[j]到第j个新元组(对于j = 1..N),然后递归。当i = list.size时,表示元组已完成,我们可以使用它(例如,将其打印出来)。(可以使用构造函数复制列表)。
package sample;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import java.util.function.Consumer;
public class SampleCombinations {
public static void main(String[] args) {
Map<String, List<String>> map = new TreeMap<>();
map.put("x", Arrays.asList("a", "b", "c"));
map.put("y", Arrays.asList("0", "1", "2", "3"));
map.put("z", Arrays.asList("!", "-", "=", "%"));
ArrayList<Entry<String, List<String>>> entries = new ArrayList<>(map.entrySet());
System.out.println(entries);
printCombinations(entries);
}
private static void printCombinations(List<Entry<String, List<String>>> entries) {
Consumer<List<String>> cons = list -> System.out.println(list);
generateComb(entries, cons, 0, new LinkedList<>());
}
private static void generateComb(List<Entry<String, List<String>>> entries,
Consumer<List<String>> consumer, int index, List<String> currentTuple) {
/*
* terminal condition: if i==entries.size the tuple is complete
* consume it and return
*/
if(index==entries.size()) {
consumer.accept(currentTuple);
}
else {
/*
* get all elements from the i-th list, generate N new tuples and recurse
*/
List<String> elems = entries.get(index).getValue();
for (String elem:elems) {
// copy the current tuple
LinkedList<String> newTuple = new LinkedList<>(currentTuple);
newTuple.add(elem);
generateComb(entries, consumer, index+1, newTuple);
}
}
}
}