Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a value to terms in a Map

Tags:

java

java-8

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.

like image 834
Richard Fowler Avatar asked Feb 01 '17 12:02

Richard Fowler


People also ask

How do you add value to a map set?

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.

How do you store a value on a map?

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.

How do you add a string value to a string map?

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.

How do you call a value from a map?

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.


2 Answers

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.

like image 103
Alexis C. Avatar answered Sep 25 '22 01:09

Alexis C.


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-

like image 22
Bathsheba Avatar answered Sep 25 '22 01:09

Bathsheba