is there any way to get a hold of a `Map` entry wi...
# announcements
t
is there any way to get a hold of a
Map
entry without iterating over the whole entry set? I need it to be able to change the associated value of a key repeatedly without having to find the key in the map again every time.
d
The entries in a
MutableMap
are mutable and have a
setValue
method.
As in:
Copy code
val myEntry = myMap.entries.find { it.key == myKey }
myEntry.setValue(newValue)
Oh, missed the whole "iterating the entry set" part. Nvm me.
At least you only need to do it once 😄
m
Can't you just do this?
Copy code
myMap[key] = firstValue
...
myMap[key] = secondValue
Or do you have to change the actual entry?
d
That would do the hash lookup every time.
m
Yes, but it won't iterate through the entry set.
a
the question is: do you need to change the value itself or just a property inside the value?
s
It is technically not possible at least at Oracle JDK > 1.7 because map nodes may be recreated when bucketed hash table is transformed to red-black tree
Not possible in Java.
@snrostov Are you sure? The contracts of
Map
and
Map.Entry
require that entries stay connected to the map, no?
t
damn. I guess in that case it would be better to use an array. The entries never get moved or deleted and iterating over it once to find the key is probably faster than accessing a hashmap repeatedly, since the array will be very small
s
@karelpeeters yes, sure.
Map.Entry
require that entries stay connected to the map, no?
No, javadocs says:
Copy code
* These <tt>Map.Entry</tt> objects are
     * valid <i>only</i> for the duration of the iteration; more formally,
     * the behavior of a map entry is undefined if the backing map has been
     * modified after the entry was returned by the iterator, except through
     * the <tt>setValue</tt> operation on the map entry.
👍 2