java - 将一个键值映射到 Map 中另一个键值的算法

标签 java algorithm dictionary

我有一些 map ,我想计算它们的笛卡尔积。有人可以推荐一个好的算法吗:

数据:

Key1    {100,101,102}

Key2    {200,201}

Key3    {300}

要求的输出:(顺序很重要)

100,200,300
101,200,300
102,200,300
100,201,300
101,201,300
102,201,300

Map 是动态的,因此键和值的大小可以变化。

谢谢。

最佳答案

您将希望切换到使用 LinkedHashMap,以便在遍历键时保留顺序。

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class CartesianPrint {

    public static void main(String[] args) {
        Map<Integer,List<Integer>> groupMap = new LinkedHashMap<Integer,List<Integer>>();

        groupMap.put(1,Arrays.asList(new Integer[]{100,101,102}));
        groupMap.put(2,Arrays.asList(new Integer[]{200,201}));
        groupMap.put(3,Arrays.asList(new Integer[]{300}));

        List<List<Integer>> values = new ArrayList<List<Integer>>(groupMap.values());
        int[] printList = new int[values.size()];
        print(values,printList,values.size()-1);        
    }

    static void print(List<List<Integer>> values, int[] printList, int level){
        for (Integer value: values.get(level)) {
            printList[level] = value;
            if(level == 0){
                 System.out.println(Arrays.toString(printList));
            }else{
                 print(values,printList,level-1);
            }
        }       
    }

}

关于java - 将一个键值映射到 Map 中另一个键值的算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6790530/

相关文章:

Java HashTable 使用 Bucket 方法

algorithm - 从小的二值图像中去除异常像素

algorithm - 使用 n 个标签标记网格,其中每个标签都与其他每个标签相邻

python - 将 dict 值四舍五入为 2 位小数

python - 字典只返回 for 循环中的最后一个键值对

java - Spring data Mongo 中用户聚合时排序不起作用

java - Android java.lang.NullPointerException getActionBar()

java - 空结果集异常

c# - 正确执行双三次重采样

python - 数据提取: Creating dictionary of dictionaries with lists in python