Java map.get(key) - automatically do put(key) and return if key doesn't exist?

后端 未结 7 1200
你的背包
你的背包 2020-12-04 18:44

I am sick of the following pattern:

value = map.get(key);
if (value == null) {
    value = new Object();
    map.put(key, value);
}

This ex

7条回答
  •  再見小時候
    2020-12-04 19:31

    EDIT : Note that the feature mentioned below is long deprecated, and a CacheBuilder should be used instead.

    The Guava library has a "computing map", see MapMaker.makeComputingMap(Function).

    Map map = new MapMaker().makeComputingMap(
        new Function() {
          public String apply(Stringt) {
            return new Object();
          }
      });
    

    If you need the Function several times, extract it into a utility class, and then create the Map like this (where MyFunctions.NEW_OBJECT is the static Function instance):

    Map map = new MapMaker()
        .makeComputingMap(MyFunctions.NEW_OBJECT);
    

提交回复
热议问题