创建实体类
@Data
public class Shopping {
private String name;
private List<String> children;
}
测试
public static void main(String[] args) {
ArrayList<Shopping> shoppings = new ArrayList<>();
Shopping shopping = new Shopping();
shopping.setName("内存");
ArrayList<String> strings = new ArrayList<>();
strings.add("12G");
strings.add("16G");
shopping.setChildren(strings);
Shopping shopping1 = new Shopping();
shopping1.setName("存储");
ArrayList<String> strings1 = new ArrayList<>();
strings1.add("256G");
strings1.add("512G");
shopping1.setChildren(strings1);
Shopping shopping2 = new Shopping();
shopping2.setName("颜色");
ArrayList<String> strings2 = new ArrayList<>();
strings2.add("黑色");
strings2.add("白色");
shopping2.setChildren(strings2);
shoppings.add(shopping);
shoppings.add(shopping1);
shoppings.add(shopping2);
List<List<String>> combinations = generateCombinations(shoppings);
for (List<String> combination : combinations) {
System.out.println(combination);
}
}
public static List<List<String>> generateCombinations(List<Shopping> shoppings) {
List<List<String>> result = new ArrayList<>();
generateCombinationsRecursive(shoppings, 0, new ArrayList<>(), result);
return result;
}
private static void generateCombinationsRecursive(List<Shopping> shoppings, int index, List<String> current, List<List<String>> result) {
if (index == shoppings.size()) {
result.add(new ArrayList<>(current));
return;
}
Shopping shopping = shoppings.get(index);
for (String option : shopping.getChildren()) {
current.add(shopping.getName() + ": " + option);
generateCombinationsRecursive(shoppings, index + 1, current, result);
current.remove(current.size() - 1);
}
}
效果