如前所述,参数
Collectors.toMap必须是函数,因此必须更改
0为
name-> 0(可以使用任何其他参数名称代替
name)。
但是请注意,如果中存在重复项,此操作将失败
names,因为这将导致结果映射中的键重复。要解决此问题,您可以
Stream.distinct先通过管道传递流:
Map<String, Integer> namesMap = names.stream().distinct() .collect(Collectors.toMap(s -> s, s -> 0));
或者根本不初始化这些默认值,而使用
getOrDefault或
computeIfAbsent代替:
int x = namesMap.getOrDefault(someName, 0);int y = namesMap.computeIfAbsent(someName, s -> 0);
或者,如果您想获取名称的数量,则可以使用
Collectors.groupingBy和
Collectors.counting:
Map<String, Long> counts = names.stream().collect( Collectors.groupingBy(s -> s, Collectors.counting()));



