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

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.