When i use the .putAll()
will another .putAll()
override the content of the map?
Will my map contain SomeOfMyObjects and SomeOfMyObjects?
Map<MyObject> blah = new HashMap<>();
blah.putAll('SomeOfMyObjects')
blah.putAll('SomeOfMyObjects')
Thanks!
So with this definition, it overrides existing keys with new values. Whether the documentation changed or not, putAll will put All.
HashMap. putAll() is an inbuilt method of HashMap class that is used for the copy operation. The method copies all of the elements i.e., the mappings, from one map into another. Parameters: The method takes one parameter exist_hash_map that refers to the existing map we want to copy from.
Assuming that both maps contain the same set of keys, and that you want to "combine" the values, the thing you would be looking for is a Pair class, see here for example. You simply iterate one of the maps; and retrieve values from both maps; and create a Pair; and push that in your result map.
If you see docs
Copies all of the mappings from the specified map to this map (optional operation). The effect of this call is equivalent to that of calling put(k, v) on this map once for each mapping from key k to value v in the specified map.
this call is equivalent to that of calling put(k, v)
And for as per put() method
Associates the specified value with the specified key in this map (optional operation). If the map previously contained a mapping for the key, the old value is replaced by the specified value. (A map m is said to contain a mapping for a key k if and only if m.containsKey(k) would return true.)
Not sure if anyone else finds the advice above opposing. But as a new Jenkins/Groovy user, I had to test it for myself to validate and can confirm it overwrites for "put" and "putAll".
LinkedHashMap test = [X: 1]
test.put("X", 2)
assertTrue(test["X"] == 2)
and
LinkedHashMap test = [X: 1]
LinkedHashMap test2 = [X: 2]
test.putAll(test2)
assertTrue(test["X"] == 2)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With