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

前端 未结 2 715
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.

提交回复
热议问题