合并具有重复键的Map列表

ep6jt1vc  于 2021-07-06  发布在  Java
关注(0)|答案(4)|浏览(273)

这个问题在这里已经有答案了

合并具有重复键的数组Map(8个答案)
将Map列表合并为单个Map(5个答案)
29天前关门了。
我有一份 HashMap<Integer, ArrayList<String>> 想把它们合并成一个循环。问题是,每个Map的键从0开始,因此这些键将被复制。这个 putAll() 不工作,因为它覆盖了关键点,总是给我最后的Map。
我见过使用stream合并两个Map的例子,但在我的例子中,可能有两个以上的Map。我正在尝试生成一个具有增量键的合并Map。例如:
假设列表中有2个Map(可能更多),两个键都从0开始,但以不同的值结束。
第一张Map,键从0开始到10结束
第二张Map,键从0开始到15结束
有没有可能用11开始的键添加第二张Map?最后,我需要一个合并的Map,其中第一个键开始于0,最后一个键结束于25。

ix0qys7i

ix0qys7i1#

我会迭代你拥有的任意数量的Map,然后对于你想要组合的每个Map,迭代这些条目。对于您可以使用的每个条目 computeIfAbsent 有条件地为键创建一个空列表,然后调用 addAll 价值观。例如。:

List<Map<Integer, List<String>>> maps = List.of(
        Map.of(1, List.of("hello")),
        Map.of(2, List.of("world")),
        Map.of(1, List.of("a"), 2, List.of("b"))
);

Map<Integer, List<String>> combined = new HashMap<>();
for (Map<Integer, List<String>> map : maps) {
    for (Map.Entry<Integer, List<String>> e : map.entrySet()) {
        combined.computeIfAbsent(e.getKey(), k -> new ArrayList<>()).addAll(e.getValue());
    }
}
7xzttuei

7xzttuei2#

如果你喜欢溪流方法

Map<Integer, List<String>> m1;
Map<Integer, List<String>> m2;
Map<Integer, List<String>> m3;

Map<Integer, List<String>> combined = new HashMap<>();
Stream
    .of(m1, m2, m3)
    .flatMap(m -> m.entrySet().stream())
    .forEach(e -> combined.computeIfAbsent(e.getKey(), k -> new ArrayList<>())
            .addAll(e.getValue()));
kkbh8khc

kkbh8khc3#

假设您有一个Map列表,其中每个Map的键都是范围内的整数 [0-k], [0-n], [0, r] ... 生成的Map应该是 [0 - (k+n+r..)] 下面这样的方法应该有用:

public static void main(String[] args) throws IOException {
   //example list of maps
   List<Map<Integer,List<String>>> mapList = List.of(
           Map.of( 0,List.of("foo","foo"), 
                   1,List.of("bar","bar"), 
                   2,List.of("baz","baz")),
           Map.of( 0,List.of("doo","doo"), 
                   1,List.of("gee","gee"), 
                   2,List.of("woo","woo")),
           Map.of( 0,List.of("cab","cab"), 
                   1,List.of("kii","kii"), 
                   2,List.of("taa","taa"))
   );
   AtomicInteger ai = new AtomicInteger();
   Map<Integer,List<String>> result = 
           mapList.stream()
                   .flatMap(map -> map.values().stream())
                   .collect(Collectors.toMap(list -> ai.getAndIncrement(), Function.identity()));
   result.forEach((k,v) ->{
       System.out.println(k + " : " + v);
   });
}
dbf7pr2w

dbf7pr2w4#

我知道你想要一张Map,但根据你的解释,你的最终解决方案,以及你的密钥现在是从0开始的连续整数,你可以创建一个 List<List<String>> . 在这种情况下,你可以这样做:

List<List<String>> result = mapList.stream()
               .flatMap(map->map.values().stream())
               .collect(Collectors.toList());

相关问题