You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何根据Map<String,List<Integer>>的动态条目数构造嵌套for循环

N个列表动态笛卡尔积实现方案

你需要实现的是任意数量列表的笛卡尔积计算,不需要动态生成多层for循环,用递归回溯或者迭代累加的方式即可实现,以下是可直接运行的Java代码示例:

方案1:递归实现(代码简洁,适合层数不高的场景)

首先把TreeMap的Value按固定顺序提取为列表,再通过递归逐层遍历每个列表的元素,拼接完成后输出:

import java.util.*;

public class CartesianProduct {
    public static void main(String[] args) {
        Map<String, List<Integer>> myList = new TreeMap<>();
        // 原有构造Map的代码
        List<Integer> firstList = new ArrayList<>();
        firstList.add(1);
        firstList.add(2);
        firstList.add(3);
        myList.put("1", firstList);
        List<Integer> secondList = new ArrayList<>();
        secondList.add(3);
        secondList.add(4);
        secondList.add(5);
        myList.put("2", secondList);
        // 可继续添加更多条目测试
        // List<Integer> thirdList = new ArrayList<>();
        // thirdList.add(6); thirdList.add(7);
        // myList.put("3", thirdList);

        // 按固定顺序取出所有列表(TreeMap默认按Key排序,顺序稳定)
        List<List<Integer>> allLists = new ArrayList<>(myList.values());
        // 递归计算笛卡尔积
        recursiveProduct(allLists, 0, new ArrayList<>());
    }

    /**
     * 递归计算笛卡尔积
     * @param allLists 所有待计算的列表
     * @param currentIndex 当前处理到第几个列表
     * @param currentCombination 当前已经拼接好的元素组合
     */
    private static void recursiveProduct(List<List<Integer>> allLists, int currentIndex, List<Integer> currentCombination) {
        // 已经处理完所有列表,输出当前组合
        if (currentIndex == allLists.size()) {
            // 按需求格式输出,这里用空格分隔
            for (int i = 0; i < currentCombination.size(); i++) {
                if (i > 0) System.out.print("  ");
                System.out.print(currentCombination.get(i));
            }
            System.out.println();
            return;
        }
        // 遍历当前列表的所有元素
        List<Integer> currentList = allLists.get(currentIndex);
        for (Integer num : currentList) {
            // 把当前元素加入临时组合
            currentCombination.add(num);
            // 递归处理下一个列表
            recursiveProduct(allLists, currentIndex + 1, currentCombination);
            // 回溯,移除刚加入的元素,准备处理下一个元素
            currentCombination.remove(currentCombination.size() - 1);
        }
    }
}

方案2:迭代实现(无递归栈溢出风险,适合层数较多的场景)

通过迭代逐步累加计算笛卡尔积,每次把已生成的组合和下一个列表做乘积:

public static void iterativeProduct(Map<String, List<Integer>> map) {
    List<List<Integer>> allLists = new ArrayList<>(map.values());
    // 存储临时计算结果,初始只有一个空组合
    List<List<Integer>> result = new ArrayList<>();
    result.add(new ArrayList<>());

    for (List<Integer> list : allLists) {
        List<List<Integer>> tempResult = new ArrayList<>();
        // 把已有的每个组合和当前列表的每个元素拼接
        for (List<Integer> existingCombination : result) {
            for (Integer num : list) {
                List<Integer> newCombination = new ArrayList<>(existingCombination);
                newCombination.add(num);
                tempResult.add(newCombination);
            }
        }
        // 更新结果为当前轮次的乘积结果
        result = tempResult;
    }

    // 输出所有结果
    for (List<Integer> combination : result) {
        for (int i = 0; i < combination.size(); i++) {
            if (i > 0) System.out.print("  ");
            System.out.print(combination.get(i));
        }
        System.out.println();
    }
}

直接在主方法中调用iterativeProduct(myList)即可使用。


内容的提问来源于stack exchange,提问作者Unknown Guy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 16:36:00