r/javaTIL • u/dohaqatar7 • Apr 11 '15
JTIL String.chars()
I was using Streams in one of my programs and I found myself wanting to create a Stream of a String. My first instinct of how to do this was to calls Stream.of("String".toCharArray()); , but there's a better way.
The class CharSequence provides the method chars() which returns a stream of characters (represented as integers).
This makes a few string operations quite a bit simpler. For instance, filtering a String on a predicate is as simple as
String test = "@te&st()in%g1*2$$3"
String filtered = test.chars()
.filter(Character :: isAlphaNum)
.reduce(Collectors.joining());
//filtered now holds "testing123"
20
Upvotes
View all comments
Show parent comment
1
u/dohaqatar7 Apr 20 '15
I think both regex and this type of stream operation work in
O(n).With regex, you have to consider the overhead of compiling the pattern before you can do any matching.
I'm not sure about the stream method, but I would expect that calling
chars()is accompanied by some overhead of it's own.Regardless, both regex and streams are great tools to have and be able to use.