Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/337.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何将Map转换为Map_Java - Fatal编程技术网

Java 如何将Map转换为Map

Java 如何将Map转换为Map,java,Java,它不起作用。我想将mapList复制到mapSet。您一直在为所有键添加和修改同一对象 您当前所做的可以看作是: 为了解决这个问题,在循环的每次迭代中创建一个新的集合 Map<Integer, List<String>> mapList = new TreeMap<>(); Map<Integer, Set<String>> mapSet = new TreeMap<>(); Set<String>

它不起作用。我想将mapList复制到mapSet。

您一直在为所有键添加和修改同一对象

您当前所做的可以看作是:

为了解决这个问题,在循环的每次迭代中创建一个新的集合

Map<Integer, List<String>> mapList = new TreeMap<>();
Map<Integer, Set<String>> mapSet = new TreeMap<>();
        Set<String> set = new TreeSet<>();
        for (Map.Entry<Integer, List<String>> entry : entriesSortedByValues(mapList)) {
            set.addAll(entry.getValue());
            mapSet.put(entry.getKey(), set);
        }
还可以使用将集合作为参数的构造函数

Map<Integer, List<String>> mapList = new TreeMap<>();
Map<Integer, Set<String>> mapSet = new TreeMap<>();
for (Map.Entry<Integer, List<String>> entry : entriesSortedByValues(mapList)) {
    Set<String> set = new TreeSet<>();
    set.addAll(entry.getValue());
    mapSet.put(entry.getKey(), set);
}

在for循环中添加集合

Map<Integer, List<String>> mapList = new TreeMap<>();
Map<Integer, Set<String>> mapSet = new TreeMap<>();
for (Map.Entry<Integer, List<String>> entry : entriesSortedByValues(mapList)) {
    mapSet.put(entry.getKey(), new TreeSet<>(entry.getValue()));
}

您可以使用HashSet的构造函数(如new HashSetmyList)将列表转换为Set


您必须为每个迭代创建一个新集合,而不是为所有迭代创建一个集合。如果你调试了你的代码,你会发现你一直在写同一个集合。
    for (Map.Entry<Integer, List<String>> entry : entriesSortedByValues(mapList)) {
        Set<String> set = new TreeSet<>();
        set.addAll(entry.getValue());
        mapSet.put(entry.getKey(), set);
    }
Map<Integer, List<String>> mapList = new TreeMap<>();
Map<Integer, Set<String>> mapSet = new TreeMap<>();

   for (Map.Entry<Integer, List<String>> entry : entriesSortedByValues(mapList)) {
        Set<String> set = new HashSet<String>(entry.getValue());
        mapSet.put(entry.getKey(), set);
   }