两个LinkedHashMap使用不同的泛型加入相同的键

时间:2012-02-28 11:39:32

标签: java arraylist hashmap linkedhashmap

我有两个linkedHashMaps:First sorted linkedhashmap1(Integer,Double);第二个linkedhashmap2(整数,对象)。

我想连接两个linkedHashmaps以获得Sorted linkedhashmap3(Integer,Object),使得linkedhashmap1和linkedhashmap2将以Integer值连接,这是关键并且是相同的。两个linkedhashmaps中的记录数相同。

3 个答案:

答案 0 :(得分:1)

制作hashmap2的副本并将其命名为hashmap3。然后通过将每个Double值转换为Object实例,遍历hashmap1的所有元素并将其添加到hashmap3。

例如:

// create a new map
Map<Integer, Object> hashmap3 = new HashMap<Integer, Object>();
// add all elements in hashmap2 to hasmap3
hashmap3.putAll(hashmap2);

// iterate thru all elements of hashmap1
for (Map.Entry<Integer, Double> entry : hashmap1.entrySet()) {
    // and add each element with the same key,value pair to hashmap3
    hashmap3.put(entry.getKey(), (Object)(entry.getValue()));
}

请注意,如果hashmap1和hashmap2共享一些公共密钥,hashmap2 [key]的值将被hashmap1 [key]的值覆盖。

答案 1 :(得分:0)

快速而肮脏的方法是:

. Make a new Map (hashmap3)
. Loop through the hashmap1 
. Register every item of the hashmap1, setting the key-value pairs.
. Loop through the hashmap2 map and for each item in hashmap2
   . Compare the values of the items in hashmap2 and hashmap3 of the same index  
   . If the value of hashmap2 is less than the value of the same index of hashmap3 
      . Put it in hashmap3 with the same index number it had in hashmap2
      . Shift each item in hashmap3 by 1 that have greater value than the previously inserted item.
   . If the value of hashmap2 is greater than the value of the same index of hashmap3
      .Loop in hashmap3 until you find the first item that is greater than the value of the item in hashmap2
      .Put new item on the same index you've found previously.
      .Shift each remaining item by 1 in hashmap3 that have greater value than the previously inserted. 

答案 2 :(得分:0)

以下是使用this answer中的Pair<A,B>课程执行此操作的方法:

此代码假定每个键都存在于两个映射中。

Map<Integer, Pair<Double,Object> > hashmap3 =
    new LinkedHashMap<Integer, Pair<Double,Object> >();

for (Map.Entry<Integer, Double> entry : hashmap1.entrySet()) {
    Integer key = entry.getKey();
    Object obj = hashmap2.get(key);
    hashmap3.put(key, new Pair<Double,Object>(entry.getValue(), obj));
}