我有一个哈希图,将String和HashSet作为键和值。
我正在尝试更新地图并在其中添加值。
我无法理解使用以下哪种方法-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/