如何在 Java 8 中将字符流转换为字符串 [已关闭]

2022-09-04 06:07:06

如何在Java 8中转换为a? 期望因此它给出编译错误。Stream<Character>StringCollectors.joining()CharSequence


答案 1

请参阅@jubobs解决方案链接。也就是说,在你的情况下,你可以这样做:

Stream<Character> testStream = Stream.of('a', 'b', 'c');

String result = testStream.collect(Collector.of(
    StringBuilder::new,
    StringBuilder::append,
    StringBuilder::append,
    StringBuilder::toString));

这更高性能,然后首先ping每个字符,然后,这将削减该中间步骤。map/castStringjoiningStringBuilder#append(char c)


答案 2

转换为CharacterString

Stream<Character> st = Stream.of('C','h','t');
String result = st.map(c->c.toString()).collect(Collectors.joining());
System.out.println(result);  //Cht

或者通过使用方法引用

st.map(Object::toString).collect(Collectors.joining())

在此处进行内部使用Collectors.joiningStringBuilder

或者只是通过使用forEach

StringBuilder builder = new StringBuilder();

    Stream<Character> st = Stream.of('C','h','t');

    st.forEach(ch->builder.append(ch));

推荐