Iterating a String

The chars method is a new one in the String class from the CharSequence interface. It’s useful for fluently iterating over the String’s characters. We can use this convenient internal iterator to apply an operation on the individual characters that make up the string. Let’s use it in an example to process a string. Along the way we’ll discuss a few more handy ways to use method references.

compare/fpij/IterateString.java
 
final​ ​String​ str = ​"w00t"​;
 
 
str.chars()
 
.forEach(ch -> ​System​.out.println(ch));

The chars method returns a Stream over which we can iterate, using the forEach internal iterator. We get direct read access to the characters in the String within the iterator. Here’s the result when we iterate and ...

Get Functional Programming in Java now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.