How to convert Stream<Character>
into a String
in Java 8? Collectors.joining()
expects CharSequence
hence it is giving compilation error.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With