1

我有两个linkedHashMap:首先排序linkedhashmap1(整数,双精度);第二个linkedhashmap2(整数,对象)。

我想加入两个linkedHashmaps以获得Sortedlinkedhashmap3(Integer,Object),这样linkedhashmap1和linkedhashmap2都将以整数值加入,这是键并且是相同的。两个linkedhashmap 中的记录数相同。

4

3 回答 3

1

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

例如:

// 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] 的值覆盖。

于 2012-02-28T12:14:02.583 回答
0

这是使用此答案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));
}
于 2012-02-28T15:08:13.323 回答
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. 
于 2012-02-28T12:12:07.037 回答