Два LinkedHashMap Join на одном ключе с различными универсальными - PullRequest
1 голос
/ 28 февраля 2012

У меня есть два связанных HashMaps: первый отсортированный связанный hashmap1 (Integer, Double);Второй связанныйhashmap2 (Integer, Object).

Я хочу объединить оба связанныхHashmaps, чтобы получить Сортированный связанныйhashmap3 (Integer, Object) таким образом, что оба связанных и hhmapmap, и связанныйhashmap2 будут объединены с целочисленным значением, которое является ключом итот же самый.Количество записей в обеих связанных хэш-картах одинаково.

Ответы [ 3 ]

1 голос
/ 28 февраля 2012

Сделайте копию 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].

0 голосов
/ 28 февраля 2012

Вот как вы можете сделать это, используя класс 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));
}
0 голосов
/ 28 февраля 2012

Быстрый и грязный подход будет:

. 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. 
...