Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Stream of Characters into a String in Java 8 [closed]

How to convert Stream<Character> into a String in Java 8? Collectors.joining() expects CharSequence hence it is giving compilation error.

like image 921
Saikat Avatar asked Jan 30 '19 18:01

Saikat


2 Answers

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));
like image 50
Deadpool Avatar answered Oct 21 '22 19:10

Deadpool


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/castping each character to a String first and then joining, as StringBuilder#append(char c) will cut out that intermediate step.

like image 45
Dovmo Avatar answered Oct 21 '22 20:10

Dovmo