我有一个 HashMap ,它采用 String 和 HashSet 作为键和值。 我正在尝试更新 map 并在其中添加值。
我无法理解使用以下哪种方法-
map.putIfAbsent(str.substring(i,j),new HashSet<String>).add(str); //this method gives nullpointerexception
map.computeIfPresent(str.substring(i,j),(k,v)->v).add(str);
在输出中,我可以看到同一个键被添加两次,并带有初始值和更新值。
有人请告诉我如何使用这些方法。
最佳答案
最好的方法是使用 Map#computeIfAbsent
。这样就不会不必要地创建一个新的HashSet
,并且之后它会返回该值。
map.computeIfAbsent(str.substring(i, j), k -> new HashSet<>()).add(str);
关于java - 对Java8中的HashMap感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40196669/