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

Java如何使用流函数将字符流或Object字符数组转为char数组

Java流将Character流转为char[]类型的实现方案

Java标准库的Stream API未提供char类型对应的专用基本类型流,仅有IntStream、LongStream、DoubleStream三种基本类型流实现,因此你当前写法中Stream<Character>调用无参toArray()只能得到Object[],即使用toArray(Character[]::new)也只能得到包装类型Character[],无法直接得到基本类型char[],可以通过以下两种方案实现需求:


方案1:拼接为字符串后转char数组(写法简洁)

通过收集器将流中所有字符拼接为字符串,再调用字符串的toCharArray()方法直接得到目标数组,代码可读性更高:

static public void reverseString(char[] s){
    char[] upperCaseArray = IntStream.range(0,s.length)
            .mapToObj(index -> s[index])
            .map(Character::toUpperCase)
            .collect(StringBuilder::new, StringBuilder::append, StringBuilder::append)
            .toString()
            .toCharArray();
}

方案2:直接基于IntStream处理(性能更优)

全程使用IntStream操作,避免char和Character的装箱拆箱开销,更适合处理长数组场景:

static public void reverseString(char[] s){
    char[] upperCaseArray = IntStream.range(0,s.length)
            .map(index -> Character.toUpperCase(s[index]))
            .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
            .toString()
            .toCharArray();
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 07:36:09