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>?
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);
}
}
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.
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