blog posts

loop: Tutorial for… each loop in Java

In Java, there is another form of loop (in addition to the standard for loop) for working with arrays and sets.

If you are working with arrays and sets, you can duplicate their items using another for loop structure (advanced for loop form). 

This loop type is called for-each because the loop is repeated through each array/set element.

Here is an example of repeating elements of an array using the standard for loop in Java:

  1. class ForLoop {
  2. public static void main (String [] args) {
  3. char [] vowels = {‘a’, ‘e’, ​​’i’, ‘o’, ‘u’};
  4. for (int i = 0; i <vowels.length; ++ i) {
  5. System.out.println (vowels [i]);
  6. }
  7. }
  8. }

You can also write the above code using the for-each loop:

  1. class AssignmentOperator {
  2. public static void main (String [] args) {
  3. char [] vowels = {‘a’, ‘e’, ​​’i’, ‘o’, ‘u’};
  4. // foreach loop
  5. for (char item: vowels) {
  6. System.out.println (item);
  7. }
  8. }
  9. }

The output of both codes is similar and equal to:

  1. a
  2. e
  3. i
  4. o
  5. u

The advanced for loop makes the code easier to write and more readable. Hence, it is usually recommended more than the standard form.

For each ring structure

First, let’s look at the for-each loop structure:

for (data_type item: collection) {

…

}

In the above structure,

  • collection is a collection or array in which you want to write a circle.
  • An item is a single element of the collection.

How does the for-each loop work?loop

Here’s how the for-each loop works.

  • Repeat through any component of the given array or collection,
  • Stores each item in an item.
  • And executes the body of the ring.

Example: for-each loop

The following program calculates the sum of all the elements of an array of integers.

  1. class EnhancedForLoop {
  2. public static void main (String [] args) {
  3. int [] numbers = {3, 4, 5, -5, 0, 12};
  4. int sum = 0;
  5. for (int number: numbers) {
  6. sum + = number;
  7. }
  8. System.out.println (“Sum =” + sum);
  9. }
  10. }

Output

Sum = 19

In the above program, the execution of the for-each loop is as follows:

You see a repeat of the for-each loop

  • All elements of numbers are repeated.
  • Each element is stored in the number variable.
  • The loop’s body is executed, ie, the number is added to the sum.

 

forEach() vs. Traditional for LoopLoop

Both forEach() and the traditional for loop can be used to iterate over collections and arrays. However, the forEach() method lacks the flexibility that the for loop provides.

With a traditional for loop, you have complete control over loop variables, conditions, and increments, whereas forEach() Abstracts these details:

List<String> names = List.of("Larry", "Steve", "James", "Conan", "Ellen");
for (int i = 0; i < names.size(); i++) {
    LOG.info(names.get(i));
}

Additionally, you can modify loop conditions:

for (int i = 0; i < names.size() - 1; i++) {
    LOG.info(names.get(i));
}

In the example above, the last element is skipped by adjusting the loop condition (names.size() - 1). This level of customization is not possible with forEach().

While forEach() allows operations on individual elements, it does not permit modifications to the collection. In contrast, the for loop provides more flexibility, enabling both element-specific operations and direct changes in the collection.

forEach() vs. Enhanced for Loop

At a basic level, both loops serve the same purpose: iterating over elements in a collection. However, their underlying mechanics differ—while the enhanced for loop uses an external iterator, the forEach() method relies on an internal iterator.

Internal Iterator – forEach()

An internal iterator handles iteration behind the scenes, allowing the programmer to focus solely on defining operations for each element in the collection. Instead of explicitly managing the iteration process, the Iterator ensures that elements are processed sequentially.

Here’s an example:

List<String> names = List.of("Larry", "Steve", "James", "Conan", "Ellen");
names.forEach(name -> LOG.info(name));

In the In the forEach() In the method above, a lambda expression is passed as an argument. This means that instead of manually controlling iteration, we simply specify what needs to be done with each element—the method takes care of the rest.

While forEach() simplifies code readability and reduces verbosity, the enhanced for loop may be preferable in situations where more control over iteration is needed.