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

如何通过Collectors.mapping自定义映射将字符统计结果转为Map<Character, Integer>

解决方案

你可以通过在groupingBy的下游收集器中结合Collectors.mapping,将每个字符映射为数值1,再配合Collectors.summingInt统计总数,直接得到Map<Character, Integer>类型的结果:

import java.util.function.Function;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        String str = "abcdefabcdghh";
        var charCountMap = str.chars()
                .mapToObj(i -> (char) i)
                .collect(Collectors.groupingBy(
                        Function.identity(),
                        Collectors.mapping(
                                c -> 1,  // 将每个字符映射为1
                                Collectors.summingInt(Integer::intValue)  // 对1求和得到Integer类型计数
                        )
                ));
        System.out.println(charCountMap);
    }
}

如果追求更简洁的写法,也可以直接用Collectors.summingInt作为下游收集器(逻辑和上面一致,省略显式的mapping步骤):

var charCountMap = str.chars()
        .mapToObj(i -> (char) i)
        .collect(Collectors.groupingBy(
                Function.identity(),
                Collectors.summingInt(c -> 1)
        ));

要是想基于原有的counting()结果转换类型,还可以用collectingAndThen包裹counting(),把Long类型的计数转为Integer:

var charCountMap = str.chars()
        .mapToObj(i -> (char) i)
        .collect(Collectors.groupingBy(
                Function.identity(),
                Collectors.collectingAndThen(
                        Collectors.counting(),
                        Long::intValue  // 将Long计数转为Integer
                )
        ));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 15:05:59