如何在 Java 8 中将字符流转换为字符串 [已关闭]
2022-09-04 06:07:06
如何在Java 8中转换为a? 期望因此它给出编译错误。Stream<Character>
String
Collectors.joining()
CharSequence
如何在Java 8中转换为a? 期望因此它给出编译错误。Stream<Character>
String
Collectors.joining()
CharSequence
请参阅@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/cast
String
joining
StringBuilder#append(char c)
转换为Character
String
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.joining
StringBuilder
或者只是通过使用forEach
StringBuilder builder = new StringBuilder();
Stream<Character> st = Stream.of('C','h','t');
st.forEach(ch->builder.append(ch));