How to convert Stream of Characters into a String in Java 8
Convert Character
to String
Stream<Character> st = Stream.of('C','h','t');
String result = st.map(c->c.toString()).collect(Collectors.joining());
System.out.println(result); //Cht
Or by using method reference
st.map(Object::toString).collect(Collectors.joining())
And Collectors.joining
internally uses StringBuilder
here
Or just by using forEach
StringBuilder builder = new StringBuilder();
Stream<Character> st = Stream.of('C','h','t');
st.forEach(ch->builder.append(ch));
Refer to @jubobs solution link. That is, you could do it this way in your case:
Stream<Character> testStream = Stream.of('a', 'b', 'c');
String result = testStream.collect(Collector.of(
StringBuilder::new,
StringBuilder::append,
StringBuilder::append,
StringBuilder::toString));
This is more performant then map/cast
ping each character to a String
first and then joining
, as StringBuilder#append(char c)
will cut out that intermediate step.