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 through a List

Iterating through a list is a basic operation on a collection, but over the years it’s gone through a few significant changes. We’ll begin with the old and evolve an example—enumerating a list of names—to the elegant style.

We can easily create an immutable collection of a list of names with the following code:

 
final​ ​List​<​String​> friends =
 
Arrays​.asList(​"Brian"​, ​"Nate"​, ​"Neal"​, ​"Raju"​, ​"Sara"​, ​"Scott"​);

Here’s the habitual, but not so desirable, way to iterate and print each of the elements.

collections/fpij/Iteration.java
 
for​(​int​ i = 0; i < friends.size(); i++) {
 
System​.out.println(friends.get(i));
 
}

I call this style the self-inflicted wound pattern—it’s verbose and error prone. We ...

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