我有两个不同类型的地图:
class Type3{
Type1 type1;
Type2 type2;
// getters and setters...
}
Map<Integer,Type1> map1;
Map<Integer,Type2> map2;
我想通过相同的键将它们合并到一张地图。
像他一样:
Map<Integer,Type3> map3 = // merege map1,map2.
我该怎么办?
答案 0 :(得分:2)
您可以使用Stream
来做到这一点:
Map<Integer,Type3> output =
map1.entrySet()
.stream()
.collect(Collectors.toMap(Map.Entry::getKey,
e -> new Type3(e.getValue(),map2.get(e.getKey()))));
假设Type3
具有一个接受Type1
实例和Type2
实例的构造函数。
请注意,输出Map
仅包含出现在前Map
(map1
)中的键。
如果两个输入Map
的键都可能不存在于另一个映射中,那么最好流过两个Map
的键集的并集,以免跳过任何键:
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))));
答案 1 :(得分:1)
如果Type1和Type2继承相同的Parent,则可以使用以下方法重新初始化地图:
Map<Integer,IType> mapCommon;
IType就像一个虚拟类:定义一个接口
interface IType {
}
//Program Type1 & Type2 to be like this
class Type1 implements IType{..}
class Type2 implements IType{..}