【发布时间】:2019-07-16 18:48:23
【问题描述】:
当我阅读 API 文档时,只有在映射中不存在(不存在)键时才调用映射函数,但在 Bloch 的 Effective Java 3ed p.225(稍作修改)的以下代码中,它看来这里的方法依赖于映射函数 lambda 来填充 TreeSet 以在同一个键上进行多次点击:
public class Anagrams {
public static void main(String[] args) throws IOException {
File dictionary = new File("C:\\tmp\\words.txt");
int minGroupSize = Integer.parseInt("3");
Map<String, Set<String>> groups = new HashMap<>();
try (Scanner s = new Scanner(dictionary)) {
while (s.hasNext()) {
String word = s.next();
groups.
computeIfAbsent
(alphabetize(word), (unused) -> new TreeSet<>())
.add(word);
}
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (Set<String> group : groups.values())
if (group.size() >= minGroupSize)
System.out.println(group.size() + ": " + group);
}
private static String alphabetize(String s) {
char[] a = s.toCharArray();
Arrays.sort(a);
return new String(a);
}
}
请问我错过了什么?
【问题讨论】:
-
如果键存在,
computeIfAbsent返回映射值(TreeSet)。 -
好像是这样。那么,如果 key 不存在,返回什么?方法名称 computeIfAbsent() 的语义似乎暗示映射是针对关键不存在条件,而不是关键存在条件。
-
Effective Java 第 3 版的 p225 包含一段完全不同的代码(对于第 48 项,在使流并行时要小心)。该代码来自哪个项目?
-
看括号。 ;)
-
来自
Map.computeIfAbsent的api doc:"如果指定的键尚未与值关联(或映射为null),则尝试使用给定的映射函数计算其值并将其输入到此地图中,除非为 null。"
标签: java dictionary lambda