5 Examples of Enhanced for loop in Java

Enhanced for loop was added way back in 2004 in Java and it provides an easy and cleaner way to iterate over array and Collection in Java. The introduction of forEach() in Java 8 has further improved iteration but that doesn't mean that you need to forget the for each loop. In this article, you'll see some cool examples of enhanced for loop in Java which will help you to write better and more readable code in Java. It's also less error-prone because you don't have to deal with an index like you need to with the classic "for" loop. This means no chance of one-off error, which means no risk of starting with index zero when you want to start with one or vice-versa.

Though like other for loops it also has some constraints and restrictions like you cannot remove elements during iteration, for that you need to use the Iterator.

Another limitation of the enhanced "for" loop is that you cannot go back, which means you can start from the last element and go back towards the first element. This is possible in the traditional "for" loop because you have access to the index.


Syntax of The Enhanced "for" Loop

If you are wondering how is the enhanced "for" loop looks like and what is the syntax to use it, here is an image from Cay S. Horstmann's Core Java Book Chapter 7, which clearly explains the syntax of enhanced for loop in Java:

5 Examples of Enhanced for loop in Java

You can see that you just need to declare a variable of the type your Collection holds and you are done.

Pros of enhanced for loop
1. Cleaner code, easy to write and read
2. No chance of one-off error

Cons of enhanced for loop
1. You cannot remove() elements during iteration.
2. You cannot go backward during traversal, it is always from first to last

And, if you want to learn more about enhanced for loop concepts, you can see The Complete Java MasterClass course on Udemy. One of the most comprehensive and up-to-date courses to learn Java fundamentals.


Enhanced for loop Examples in Java

Here are five examples of enhanced for loop in Java

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
 
public class Main {
 
  public static void main(String args[]) {
 
    // Example 1 - You can use enhanced for loop with array
    String[] currencies = { "JPY", "AUD", "USD" };
 
    for (String currency : currencies) {
      System.out.println(currency);
    }
 
    // Example 2 - You can use enhanced for loop with collection
    // e.g. list, set or queue
    Collection<Integer> primes = new HashSet<>();
    primes.add(2);
    primes.add(3);
    primes.add(5);
 
    for (Integer prime : primes) {
      System.out.println(prime);
    }
 
    // Example 3 - You can use any object which implements Iterable
    // with enhanced for loop in Java
    MyIterable<Integer> custom = new Main.MyIterable<>(Arrays.asList(1, 2, 3));
    for (Integer number : custom) {
      System.out.println(number);
    }
 
    // Example 4 - You cannot remove elements when iterating over
    // Collection using enhanced for loop, as iterator's remove()
    // method is not accessible and Collection's remove() method
    // will throw ConcurrentModificationException
    List<Integer> multiples = new ArrayList<>();
    multiples.add(10);
    multiples.add(20);
    multiples.add(30);
 
    for (Integer i : multiples) {
      // multiples.remove(i);
    }
 
    // Example 5 - Iterating over a two dimensional array using
    // enhanced for loop
    int[][] cubes = { { 2, 4 }, { 3, 9 }, { 4, 16 } };
 
    for (int[] numbers : cubes) {
      for (int i : numbers) {
        System.out.println(i);
      }
    }
 
  }
 
  private static class MyIterable<T> implements Iterable<T> {
    private Collection<T> repository;
 
    public MyIterable(Collection<T> source) {
      repository = source;
    }
 
    @Override
    public Iterator<T> iterator() {
      return repository.iterator();
    }
 
  }
}

That's all about how to iterate over Collection or array using enhanced for loop in Java. These examples clearly demonstrate the power and limitation of enhanced for loop in Java.  Try to use it on your day-to-day coding to improve the readability of your Java code.


Related Java 8 Tutorials
If you are interested in learning more about the new features of Java 8, here are my earlier articles covering some of the important concepts of Java 8
  • Java 8 Interview Questions Preparation Course (free)
  • How to use Stream class in Java 8 (tutorial)
  • Difference between abstract class and interface in Java 8? (answer)
  • What is the default method in Java 8? (example)
  • How to format/parse the date with LocalDateTime in Java 8? (tutorial)
  • How to use peek() method in Java 8 (example)
  • How to use filter() method in Java 8 (tutorial)
  • 5 Books to Learn Java 8 from Scratch (books)
  • 20 Examples of Date and Time in Java 8 (tutorial)
  • How to sort the map by keys in Java 8? (example)
  • How to convert List to Map in Java 8 (solution)
  • How to sort the may by values in Java 8? (example)
  • How to join String in Java 8 (example)
  • 5 Free Courses to learn Java 8 and 9 (courses)

Thanks for reading this article so far. If you like this tutorial then please share it with your friends and colleagues. If you have any questions, doubt or feedback about this tutorial and my explanation then please drop a note.

P. S. - If you are looking for some free courses to learn recent changes on Java 8 and Java 9 then you can also see this list of Free Java 8 and 9 Courses for Programmers

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.