最初にソートされたlinkedhashmap1(整数、倍精度)。2番目のlinkedhashmap2(整数、オブジェクト)。
私は両方のlinkedHashmapを結合してSorted linkedhashmap3(Integer, Object)を取得し、linkedhashmap1とlinkedhashmap2の両方がキーであり同じである整数値で結合されるようにしたいと考えています。両方のlinkedhashmapのレコード数は同じです。
最初にソートされたlinkedhashmap1(整数、倍精度)。2番目のlinkedhashmap2(整数、オブジェクト)。
私は両方のlinkedHashmapを結合してSorted linkedhashmap3(Integer, Object)を取得し、linkedhashmap1とlinkedhashmap2の両方がキーであり同じである整数値で結合されるようにしたいと考えています。両方のlinkedhashmapのレコード数は同じです。
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] の値で上書きされることに注意してください。
この回答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));
}
高速で汚いアプローチは次のようになります。
. 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.