I'm trying to add specific values to a map in Java
, where the key is quite complex, but the value is a simple Double.
Currently I'm using, where foos is an instance of java.util.TreeMap<Foo, Double>
, and amount
is a Double
, code like:
for (java.util.Map.Entry<Foo, Double> entry : foos.entrySet()){
foos.put(entry.getKey(), entry.getValue() + amount);
}
but this looks quite dirty in that I have to reinsert the element, and I'm worried about invalidating the iterator.
Is there a better way of doing this? I'm using the latest version of Java.
1. Add values to a Map. The standard solution to add values to a map is using the put() method, which associates the specified value with the specified key in the map. Note that if the map already contains a mapping corresponding to the specified key, the old value will be replaced by the specified value.
a) The values can be stored in a map by forming a key-value pair. The value can be retrieved using the key by passing it to the correct method. b) If no element exists in the Map, it will throw a 'NoSuchElementException'. c) HashMap stores only object references.
Maps are associative containers that store elements in a specific order. It stores elements in a combination of key values and mapped values. To insert the data in the map insert() function in the map is used.
The get() method of Map interface in Java is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. It returns NULL when the map contains no such mapping for the key.
Since you only want to modify the values, you can use Map#replaceAll
:
foos.replaceAll((k, v) -> v + amount);
merge
is useful if you potentially have new keys to insert, but that's not your case since you are iterating over the same set of keys.
One way is to use the Map#merge
that, since Java version 8, has been available:
for (java.util.Map.Entry<Foo, Double> entry : foos.entrySet()){
foos.merge(entry.getKey(), amount, Double::sum);
}
Note the use of the method reference symbol ::
, not to be confused with the scope resolution operator of C++.
Here I'm using the "canned" function Double::sum
but you can have lots of fun building your own which makes this approach particularly powerful. For more details see https://docs.oracle.com/javase/8/docs/api/java/util/Map.html#merge-K-V-java.util.function.BiFunction-
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