July 2023
Intermediate to advanced
276 pages
6h 55m
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 style and evolve an example—enumerating a list of names—to the elegant style.
We can easily create a list of names with the following code:
| | final List<String> friends = |
| | Arrays.asList("Brian", "Nate", "Neal", "Raju", "Sara", "Scott"); |
To create an immutable list, we may use the more recently introduced function List.of() instead of Arrays.asList().
Here’s the habitual, but not so desirable, way to iterate and print each of the elements.
| | for(int i = 0; i < friends.size(); i++) { |
| | System.out.println(friends.get(i)); ... |
Read now
Unlock full access