You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Lambda将List<String>转为Map<String, Long>统计元音数量

将List转换为Map<String, Long>(按字符串统计元音数量)

需求

把List<String>转换为Map<String, Long>,其中键为原字符串,值为该字符串包含的元音(a/e/i/o/u)数量。

给定输入

List<String> myStrings = Arrays.asList("broom", "monsoon");

期望输出

Map<String, Long> stringToNumberOfVowels = Map.of("broom", 2L, "monsoon", 3L);

尝试的代码

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

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

当前问题

上述代码仅能处理单个字符串,无法批量处理列表中的多个元素。

解决方案

直接遍历列表中的每个字符串,对每个字符串单独计算元音数量,再通过Collectors.toMap收集为目标Map即可,逻辑更简洁清晰:

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class VowelCountMap {
    public static void main(String[] args) {
        List<String> myStrings = Arrays.asList("broom", "monsoon");
        
        Map<String, Long> vowelsMap = myStrings.stream()
                .collect(Collectors.toMap(
                        Function.identity(), // 键为原字符串
                        s -> s.chars()
                                .filter(c -> "aeiou".indexOf(c) != -1) // 筛选元音字符
                                .count() // 统计元音数量
                ));
        
        // 输出验证
        vowelsMap.forEach((str, count) -> System.out.println(str + " ==> " + count));
    }
}

代码说明

  1. 用myStrings.stream()替代Stream.of("broom"),遍历整个列表的所有字符串
  2. Collectors.toMap直接将每个字符串映射为键,对应的元音统计数映射为值
  3. 对每个字符串s,通过chars()转为字符流,筛选出元音后用count()得到数量,作为Map的值

运行后输出:

broom ==> 2
monsoon ==> 3

内容的提问来源于stack exchange,提问作者Raoul Duke

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 23:35:20