Putting a new value into a Map if not present, or adding it if it is

前端 未结 2 699
Happy的楠姐
Happy的楠姐 2021-01-01 23:03

I have a java.util.Map for a key-type class Foo. Let\'s call the instance of the map map.

I want to add {

相关标签:
2条回答
  • 2021-01-01 23:23

    You can do:

    map.put(foo, f + map.getOrDefault(foo, 0d));
    

    The value here will be the one that corresponds to foo if present in the Map or 0d, otherwise.

    0 讨论(0)
  • 2021-01-01 23:29

    this is what the merge function on maps is for.

    map.merge(foo, f, (f1, f2) -> f1 + f2)
    

    this can be reduced even further to

    map.merge(foo, f, Double::sum)
    

    it is basically the equivalent of

    if(map.contains(foo)){
        double x = map.get(foo);
        map.put(foo, x + f)
    } else {
        map.put(foo, f)      
    }
    
    0 讨论(0)
提交回复
热议问题