如何使用 Lambda 将 List<String> 转换为 Map<String, Long>,其中键是字符串,值是元音数量?

Rao*_*uke 0 java lambda dictionary java-stream collectors

鉴于:

List<String> myStrings = Arrays.asList("broom", "monsoon");
Run Code Online (Sandbox Code Playgroud)

返回:

Map<String, Long> stringToNumberOfVowels = Map.of("broom", 2, "monsoon", 3);
Run Code Online (Sandbox Code Playgroud)

这是我尝试过的:

Map<String, Long> vowelsMap = Stream.of("broom").flatMapToInt(String::chars).filter("aeiou".indexOf(c) >= 0).mapToObj(c -> "aeiou".indexOf(c)>=0 ? "broom" : "").collect(Collectors.groupingBy(Function.indenty(), Collectors.counting()));

for(Map.Entry<String, Long> a : vowelsMap.entrySet()) { System.out.println(a.getKey() + "==>"); System.out.println(a.getValue()); }
Run Code Online (Sandbox Code Playgroud)

我的输出(仅适用于流中传递的 1 个字符串):

扫帚==> 2

期望的输出:

扫帚==> 2

季风==> 3

YCF*_*F_L 5

您的逻辑有点复杂,一种简单的方法是使用流收集,Collectors::toMap如下所示:

Map<String, Long> vowelsMap = myStrings.stream()
        .collect(Collectors.toMap(Function.identity(), 
                str -> str.chars().filter(c -> "aeiou".indexOf(c) >= 0).count()));
Run Code Online (Sandbox Code Playgroud)

  • 使用正则表达式,其中简单的循环或流同样简单且可读,就像使用大锤悬挂一幅画一样。它可能有效,但我不认为它是完成这项工作的正确工具。我发现提供的答案更清晰,并且它可能优于正则表达式解析、匹配和替换。 (4认同)