我想要什么:[”Einstein”, “ist”, “kein”, “Stein”] ⇒ {”Einstein”=2, “kein”=1, “Stein”=1} 我想使用 Stream 将字符串列表转换为查找所有“ei”实例的映射。
我的代码陷入无限循环:
List<String> L5 = List.of("Einstein", "ist", "kein", "Stein");
Pattern P = Pattern.compile("[Ee]i");
Map<String, Integer> result = L5.stream().filter(S -> P.matcher(S).find()).collect(
Collectors.toMap(i -> i, i -> {
int count = 0;
while (P.matcher(i).find()) {
count++;
}
return count;
}));
System.out.println(result);
我想计算地图中“ei”的实例(特别是使用流)
问题出在线上
while (P.matcher(i).find())
,每次调用P.matcher(i)
都在创建一个新的匹配器,因此它变成了无限循环。P.matcher(i)
分配为变量,以便在同一个 find()
实例上调用 Matcher
。
...
Matcher matcher = P.matcher(i);
while (true) {
if (!matcher.find()) break;
count++;
}
return count;
...