简体   繁体   English

将两张不同类型的地图合并为一张地图

[英]Merge two map with different type to one map

I have two map from different type:我有两张不同类型的地图:

class Type3{
  Type1 type1;
  Type2 type2;

// getters and setters...

}


Map<Integer,Type1> map1;
Map<Integer,Type2> map2;

I want to merge them to one map by same key.我想通过相同的键将它们合并到一张地图。 like his:喜欢他的:
Map<Integer,Type3> map3 = // merege map1,map2.

How can I do it?我该怎么做?

You can do it with Stream s:你可以用Stream来做到这一点:

Map<Integer,Type3> output =
    map1.entrySet()
        .stream()
        .collect(Collectors.toMap(Map.Entry::getKey,
                                  e -> new Type3(e.getValue(),map2.get(e.getKey()))));

Assuming Type3 has a constructor that accepts a Type1 instance and a Type2 instance.假设Type3有一个接受Type1实例和Type2实例的构造函数。

Note that the output Map will contain only keys that appear in the first Map ( map1 ).请注意,输出Map将仅包含出现在第一个Map ( map1 ) 中的键。

If both of the input Map s may have keys not present in the other map, it would be better to stream over the union of the key sets of both Map s, in order not to skip any keys:如果两个输入Map s 可能都有另一个 map 中不存在的键,那么最好流式传输两个Map s 的键集的并集,以免跳过任何键:

Set<Integer> allKeys = new HashSet<> (map1.keySet());
allKeys.addAll(map2.keySet());
Map<Integer,Type3> output =
    allKeys.stream()
           .collect(Collectors.toMap(Function.identity(),
                                     key -> new Type3(map1.get(key),map2.get(key))));

If Type1 and Type2 inherits the same Parent, you can re-initialise your Map with the following:如果 Type1 和 Type2 继承同一个 Parent,您可以使用以下内容重新初始化您的 Map:

Map<Integer,IType> mapCommon;

IType would be like a dummy class: Define an interface IType 就像一个虚拟类:定义一个接口

interface IType {

}
//Program Type1 & Type2 to be like this

class Type1 implements IType{..}

class Type2 implements IType{..}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM