🗃️ Collection Iteration in Java

Looping over a collection is an essential technique in every programming language. Here are some methods with examples you can use in Java.

Let us assume we have some collection of Employee objects (referenced here as walter, jesse and mike):

var employees = new ArrayList<Employee>();

employees.add(walter);
employees.add(jesse);
employees.add(mike);

“C-Style” for loop

For some integer i that is initialized to zero, while i is less than the size of the employees collection, add one to i.

for (int i = 0; i < employees.size(); i ++) {
    //
}

This is the most explicit looping construct, and is easiest to understand for beginners. This is the best option when you have a need to reference an object or property by index.

Foreach loop

For each employee of type Employee in the employees collection.

for (Employee employee : employees) {
    //
}

Very readable and a little cleaner if you have no use for referencing indices within the loop.

While loop

While a condition is true, perform statements within the body of the loop.

int index = 0;

while (index < employees.size()) {
    //
    index ++;
}

One downside to this construct is the need to maintain your own index by defining it before the loop and iterating it within the body of the loop. It is more common to see a while loop used by testing a boolean variable that is updated once some condition is met.

On the plus side, it is very readable.

Streams

employees.stream().forEach();

This method is great because it allows developers to take advantage of parallel processing by leveraging the language construct. It’s incredibly concise and expressive.

The forEach method is considered a “terminal method” in the stream pipeline, which needs to come at the end of a stream. You can chain any number of methods following .stream(). Some methods available to use in streams are:

  • filter()
  • map()
  • reduce()
  • collect()

Stream methods accept lambdas (also referred to as an anonymous function) as parameters. This syntax may take a little getting used to at first.

Leave a comment

Your email address will not be published. Required fields are marked *