A concise method for traversing a list is by using a for-each loop. This type of loop extracts each item from the list (or set) sequentially, enabling us to iterate through the collection and execute a task on each element.
This is the standard structure:
for(datatype loopVariable : iterableCollectionVariable){ // for loop body // perform the action here }
That's just an abstract representation. The loopVariable
denotes the current element undergoing iteration. It's a local variable that's only accessible within the for loop's scope. The iterableCollectionVariable
can be a list, a set, or a custom iterable (which we'll talk about in the advanced courses). The datatype of loopVariable
must match the datatype of iterableCollectionVariable
's elements.
Here's a concrete implementation:
Integer[] numbers = new Integer[] {5, 10}; for(Integer num : numbers){ // perform some action on num here }
This can be read as "For each num
in numbers
perform some action". Let's fix the mess we made in the intro lesson by cleaning up calculateSum()
. As a refresher, this is what we had:
Integer[] numbersToSum = new Integer[] {5, 10, 2, 3}; Integer sumOfIntegers = calculateSum(numbersToSum); // sumOfIntegers is 20 public Integer calculateSum(Integer[] numbers){ Integer sum = 0; sum += numbers[0]; sum += numbers[1]; sum += numbers[2]; sum += numbers[3]; return sum; }
Replacing calculateSum()
's body with a for-each loop gives us:
Integer[] numbersToSum = new Integer[] {5, 10, 2, 3}; Integer sumOfIntegers = calculateSum(numbersToSum); public Integer calculateSum(Integer[] numbers){ Integer sum = 0; // sum should be declared and initialized outside of the for loop for(Integer num : numbers) { sum += num; } return sum; // so it can be referenced once the loop terminates }
The sum
is declared and initialized to 0. The loop will iterate over numbers
using num
to reference each individual element. num
will first reference 5, then 10, then 2, and finally 3. With each iteration, num
will be added to the running total sum
. After the iteration of all elements is complete, the program will automatically exit the loop and proceed to execute the next line of code.
We now have scalable code that loops through each element and computes the sum, irrespective of numbers
size.