为什么我的 while(matcher.find()) 进入死循环?我在 Streams 中使用它

问题描述 投票:0回答:1

我想要什么:[”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”的实例(特别是使用流)

java-stream matcher
1个回答
0
投票

问题出在线上

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;
                    ...
© www.soinside.com 2019 - 2024. All rights reserved.