Home > Software engineering >  How can i convert String to Character Stream using streamAPI?
How can i convert String to Character Stream using streamAPI?

Time:01-06

String st = "FindCaptialWords";

Can we convert above string to character stream using StreamApi?

CodePudding user response:

To get the Stream<Character>, existing IntStream provided by String::chars has to be converted:

static Stream<Character> getCharStream(String str) {
    return Optional.ofNullable(str)
        .map(s -> s.chars().mapToObj(c -> (char) c))
        .orElse(Stream.empty());
}

CodePudding user response:

I just use

Stream<Character> foo = st.chars().mapToObj(c -> Character.valueOf((char) c));

though a stream of codepoints becomes much more useful than a stream of chars as soon as you need to deal with text outside of the BMP since a single char/Character can't hold those values, and so you're back to working with an IntStream as returned by st.codePoints().

  •  Tags:  
  • Related