java 将键和值从一个映射复制到另一个映射

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12777692/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 10:10:54  来源:igfitidea点击:

Copying keys and values from one map to another map

javalistmapset

提问by nitiger

I'm trying to copy the keys and values from one map, map1, into another map, map2. The values in map 1 are stored in a set and map 2 should store map1's values in a list. The keys in each should map the same in both maps.

我试图将键和值从一个地图 map1 复制到另一个地图 map2。映射 1 中的值存储在一个集合中,映射 2 应将映射 1 的值存储在一个列表中。每个映射中的键应该在两个映射中映射相同。

I could loop through the keys in map1 then add those keys to map 2. And have another inner for loop to add each set's elements to the list in map2 but I'm not sure if this is a right way to go about it, or even correct.

我可以遍历 map1 中的键,然后将这些键添加到 map 2。并有另一个内部 for 循环将每个集合的元素添加到 map2 中的列表中,但我不确定这是否是正确的方法,或者甚至正确。

public static <K, V> void changeSetToList (Map<K, Set<V>> map1, Map<K, List<V>> map2) {
for (Map.entry<K, Set<V>> entry : m1.keys()) 
  for (List<V> l : m1.values()) 
      m2.put(entry.getKey(), l.getValue());

}

}

I haven't compiled or tested it yet though. No access to computer.

我还没有编译或测试它。无法访问计算机。

采纳答案by Rohit Jain

You can iterate through the Mapand use new ArrayList(Collections)constructor to create a List out of the Setstored in original Map.. And put it into new Map..

您可以遍历Map并使用new ArrayList(Collections)构造函数从Set存储在原始 Map 中创建一个 List .. 并将其放入 new Map ..

    Map<String, Set<String>> givenMap = new HashMap<String, Set<String>>();
    Map<String, List<String>> newMap = new HashMap<String, List<String>>();

    Set<String> newSet = new HashSet<String>();
    newSet.add("rohit");

    givenMap.put("a", newSet);
    givenMap.put("b", newSet);
    givenMap.put("c", newSet);

    for (String str: givenMap.keySet()) {
        newMap.put(str, new ArrayList<String>(givenMap.get(str)));
    }

    for(String str:newMap.keySet()) {
        System.out.println(newMap.get(str));
    }

And if you want to use a Generic method..You need to change your method to this: -

如果您想使用通用方法..您需要将您的方法更改为:-

public static <K, V> void changeSetToList (Map<K, Set<V>> givenMap, 
        Map<K, List<V>> newMap) {

    for (K str: givenMap.keySet()) {
        newMap.put(str, new ArrayList<V>(givenMap.get(str)));
    }

    for(K str:newMap.keySet()) {
        System.out.println(newMap.get(str));
    }
}