Java – add values to terms in the map

I'm trying at @ L_ 403_ 0 @ to add a specific value to the map, where the key is very complex, but the value is a simple double

I'm currently using it, where foos is Java util. Treemap < foo, double >, and amount is double. The code is as follows:

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

But it looks dirty. I have to reinsert the element. I'm worried about invalidating the iterator

Is there a better way? I am using the latest version of Java

Solution

Since you only want to modify the value, you can use map#replaceall:

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

Merge is useful if you may have new keys to insert, but this is not the case because you iterate over the same set of keys

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>