February 2014
Intermediate to advanced
160 pages
4h 59m
English
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 ...