我有一个多值Hashmap
(技术上是LinkedHashMap
):
private LinkedHashMap<String, ArrayList<BodyPart>> bodyParts = new LinkedHashMap<>();
我想查找与给定键关联的值的数量。但是,如果键不存在,bodyParts.get("sample key")
返回 null
,而我希望它返回 0(因为与那个键)。
我可以在 if
语句中屏蔽它:
int numberOfValues;
if(bodyParts.containsKey("sample"){
numberOfValues = bodyParts.get("sample").size();
}
但我想知道是否有更简单/更好的方法来做到这一点?我已阅读 computeIfPresent
的文档,但说实话,我并没有真正理解它。
最佳答案
使用Map.getOrDefault(Object key, V defaultValue)
.
Returns the value to which the specified
key
is mapped, ordefaultValue
if this map contains no mapping for the key.
关于java - 多值 HashMap 值的 "Size or zero",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56325860/