Как получить объединение TreeMaps с парой ключевых значений

У меня есть несколько временных TreeMap, которые я хотел бы объединить в одну Super TreeMap (объединение меньших TreeMap).

Общий тип моих TreeMaps

TreeMap<String,Set<Integer>>

Когда я пытаюсь вызвать SuperTreeMap.addALL(temp), я получил следующую ошибку

Error: cannot find symbol.

2 ответа

Вы не можете объединить все Set как значения с putAll, Каждый новый Set заменит существующий. Вы должны сделать это по-мужски:

Map<String, Set<Integer>> map = new TreeMap<>();
Map<String, Set<Integer>> map1 = new TreeMap<>();
Map<String, Set<Integer>> map2 = new TreeMap<>();

map1.put("one", new HashSet<>());
map1.get("one").add(1);
map1.get("one").add(2);
map1.get("one").add(3);

map1.put("two", new HashSet<>());
map1.get("two").add(1);
map1.get("two").add(2);
map1.get("two").add(3);

map2.put("one", new HashSet<>());
map2.get("one").add(4);
map2.get("one").add(5);
map2.get("one").add(6);

map2.put("two", new HashSet<>());
map2.get("two").add(4);
map2.get("two").add(5);
map2.get("two").add(6);

for (Map<String, Set<Integer>> m : Arrays.asList(map1, map2)) {
    for (Map.Entry<String, Set<Integer>> entry : m.entrySet()) {
        if (!map.containsKey(entry.getKey()))
            map.put(entry.getKey(), new HashSet<>());
        map.get(entry.getKey()).addAll(entry.getValue());
    }
}

Вы можете использовать Streams, чтобы объединить записи двух карт и внутри них элементы двух коллекций:

      Map<String, Set<Integer>> map1 = Map.of("one",Set.of(1,2,3),"two",Set.of(1,2,3));
Map<String, Set<Integer>> map2 = Map.of("one",Set.of(4,5,6),"two",Set.of(4,5,6));

Map<String, Set<Integer>> map3 = Stream.of(map1, map2)
        // Stream<Map.Entry<String,Set<Integer>>>
        .flatMap(map -> map.entrySet().stream())
        .collect(Collectors.toMap(
                // key is the same
                Map.Entry::getKey,
                // value is the same
                Map.Entry::getValue,
                // combining elements of two collections
                (set1, set2) -> Stream.of(set1, set2)
                        .flatMap(Set::stream)
                        // collectionFactory
                        .collect(Collectors.toCollection(TreeSet::new)),
                // mapFactory
                TreeMap::new));

System.out.println(map3); // {one=[1, 2, 3, 4, 5, 6], two=[1, 2, 3, 4, 5, 6]}
Другие вопросы по тегам