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

前端 未结 2 698
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: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)      
    }
    

提交回复
热议问题