O'Reilly logo

Functional Programming in Java by Venkat Subramaniam

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required