如何使用键值对获得TreeMaps的联合

时间:2018-04-24 03:23:51

标签: java set treemap set-union

我有几个临时的TreeMaps,我想将它组合成一个Super TreeMap(较小的TreeMaps的联合)。

我的TreeMaps的泛型类型是

TreeMap<String,Set<Integer>>

当我尝试调用SuperTreeMap。 addALL (temp)时,我收到以下错误

Error: cannot find symbol.

2 个答案:

答案 0 :(得分:0)

您可以使用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()); } } 。你必须勇敢地做到这一点:

try (Realm realm = Realm.getDefaultInstance()) {
    realm.removeAllChangeListeners();
    realm.executeTransaction(Realm::deleteAll);
}

答案 1 :(得分:0)

您可以创建一个自定义 addALL 方法来组合两个地图的条目并在其中组合两个集合的元素:

/**
 * Combines the entries of several maps into the {@link TreeMap}
 * and the elements of sets inside them into the {@link TreeSet}.
 *
 * @param maps the collection of maps to be combined
 * @param <T>  the type of keys of maps
 * @param <U>  the type of elements of sets
 * @return combined map of sets
 */
public static <T, U> Map<T, Set<U>> addAll(Collection<Map<T, Set<U>>> maps) {
    return maps.stream()
            // Stream<Map.Entry<String,Set<Integer>>>
            .flatMap(map -> map.entrySet().stream())
            // stream of map entries into one map
            .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.concat(set1.stream(), set2.stream())
                            // collectionFactory
                            .collect(Collectors.toCollection(TreeSet::new)),
                    // mapFactory
                    TreeMap::new));
}
// test
public static void main(String[] args) {
    Map<String, Set<Integer>>
            map1 = Map.of("one", Set.of(1, 2, 3), "two", Set.of(1, 2, 3)),
            map2 = Map.of("one", Set.of(4, 5, 6), "two", Set.of(4, 5, 6)),
            // combine the entries of two maps into one map
            map3 = addAll(Set.of(map1, map2));
    // output
    System.out.println(map3);
    // {one=[1, 2, 3, 4, 5, 6], two=[1, 2, 3, 4, 5, 6]}
}

另见:How do I take the union of sets?