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?
解决方案
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
E.g.
public class Foo {
public static void main(String[] args) {
String x = "new";
Stream characters = x.chars().mapToObj(i -> (char) i);
characters.forEach(System.out::println);
}
}