HashMap to return default value for non-found keys?

后端 未结 14 2207
别跟我提以往
别跟我提以往 2020-11-27 14:05

Is it possible to have a HashMap return a default value for all keys that are not found in the set?

14条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-27 14:09

    Use Commons' DefaultedMap if you don't feel like reinventing the wheel, e.g.,

    Map map = new DefaultedMap<>("[NO ENTRY FOUND]");
    String surname = map.get("Surname"); 
    // surname == "[NO ENTRY FOUND]"
    

    You can also pass in an existing map if you're not in charge of creating the map in the first place.

提交回复
热议问题