Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a String to a java.util.Stream<Character>

Sometimes I want to do something simple with each character in a string. Unfortunately, because a string is immutable, there is no good way of doing it except looping through the string which can be quite verbose. If you would use a Stream instead, it could be done much shorter, in just a line or two.

Is there a way to convert a String into a Stream<Character>?

like image 376
Loovjo Avatar asked Sep 09 '15 05:09

Loovjo


2 Answers

You can use chars() method provided in CharSequence and since String class implements this interface you can access it. The chars() method returns an IntStream , so you need to cast it to (char) if you will like to convert IntStream to Stream<Character>

E.g.

public class Foo {

    public static void main(String[] args) {
        String x = "new";

        Stream<Character> characters = x.chars().mapToObj(i -> (char) i);
        characters.forEach(System.out::println);
    }
}
like image 85
sol4me Avatar answered Oct 02 '22 23:10

sol4me


It's usually more safe to use stream of code points which is IntStream:

IntStream codePoints = string.codePoints();

This way Unicode surrogate pairs will be merged into single codepoint, so you will have correct results with any Unicode symbols. Example usage:

String result = string.codePoints().map(Character::toUpperCase)
        .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
        .toString();

Also note that you avoid boxing, thus it might be even more effective than processing Stream<Character>.

Another way to collect such stream is to use separate StringBuilder:

StringBuilder sb = new StringBuilder();
String result = string.codePoints().map(Character::toUpperCase)
                      .forEachOrdered(sb::appendCodePoint);

While such approach looks less functional, it may be more efficient if you already have a StringBuilder or want to concatenate something more later to the same string.

like image 28
Tagir Valeev Avatar answered Oct 02 '22 23:10

Tagir Valeev