Adding a value to conditions on a map

I am trying to add specific values ​​to a map in Java , where the key is quite complex, but the value is a simple Double.

I am currently using where foos is an instance of java.util.TreeMap<Foo, Double> , and amount is Double , a code like:

 for (java.util.Map.Entry<Foo, Double> entry : foos.entrySet()){ foos.put(entry.getKey(), entry.getValue() + amount); } 

but it looks pretty dirty because I need to reinsert the element and I am worried about the validity of the iterator.

Is there a better way to do this? I am using the latest version of Java.

+6
source share
3 answers

Since you want to change the values, you can use Map#replaceAll :

 foos.replaceAll((k, v) -> v + amount); 

merge is useful if you have new keys to insert, but this is not your case, since you are repeating the same set of keys.

+9
source

One way is to use Map#merge , which, since a version of Java 8 is available:

 for (java.util.Map.Entry<Foo, Double> entry : foos.entrySet()){ foos.merge(entry.getKey(), amount, Double::sum); } 

Pay attention to the use of the reference symbol of the :: method so as not to be confused with the C ++ scope resolution operator.

Here I use the canned Double::sum function, but you can have a lot of fun creating your own, which makes this approach especially powerful. See https://docs.oracle.com/javase/8/docs/api/java/util/Map.html#merge-KV-java.util.function.BiFunction- for more details.

+6
source

You can just use entry.setValue . The documentation states:

Replaces the value corresponding to this record with the specified value (optional operation). (It is recorded on the card.)

So:

 for (java.util.Map.Entry<Foo, Double> entry : foos.entrySet()){ entry.setValue(entry.getValue() + amount)); } 
+4
source

Source: https://habr.com/ru/post/1014620/