gpt4 book ai didi

java - 将两个 HashMap 组合成第三个

转载 作者:行者123 更新时间:2023-11-29 05:52:46 28 4
gpt4 key购买 nike

假设我在下面的每个类中都有一个对象,我将每个对象放在一个散列表中,其中 IDnumber 是两个映射中的键。

class1 {
int IDNumber = 123; //same person as class2
String name = John;
String company = Intel;

class2 {
int IDNumber = 123; //same person as class1
int income = 500;
int workYears = 3;
}

HashMap<Integer, class1> one = new Hashmap<Integer, class1>();
HashMap<Integer, class2> two = new HashMap<Integer, class2>();

现在,我如何将这两个 HashMap 混合成第三个 HashMap,以便我可以获得键 ID 号以及值名称、公司、收入和工作年限?

最佳答案

你不能那样做。您有两个不同的类,java 不会自动神奇地将它们合二为一。

您可以创建一个新的第三类来合并信息:

public Class3 {

public Class3(Class1 class1, Class2 class2){
//pull the info you want from each into variables in this class
}
}

然后遍历您的 map 以获取条目,为每个条目创建新的 Class3 实例并将它们放在新的 HashMap<Integer, Class3> 中。 .

//gets the keys from the hashmap
Set<Integer> keys = one.keySet();
//merge the keys from the second hashmap
keys.addAll(two.keySet());
//new hashmap
Map<Integer, Class3> newMap = new HashMap<Integer, Class3>();
for (Integer key : keys){
//create new instance and place it in the map
newMap.put(key, new Class3(one.get(key), two.get(key));
}

关于java - 将两个 HashMap 组合成第三个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13292489/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com