Java Map implementation that returns a default value instead of null

前端 未结 6 877
萌比男神i
萌比男神i 2020-12-14 06:27

I have a Map> in my code, where I\'d avoid potential null pointers if the map\'s #get() method returned an empty l

6条回答
  •  春和景丽
    2020-12-14 07:16

    Thanks to default methods, Java 8 now has this built in with Map::getOrDefault:

    Map map = ...
    map.put(1, "1");
    System.out.println(map.getOrDefault(1, "2")); // "1"
    System.out.println(map.getOrDefault(2, "2")); // "2"
    

提交回复
热议问题