Java foreach Loop


ForEach Java LoopViews 2674

We use Java foreach loop, also called Enhanced for loop to traverse through an array or collection. Using a for-each loop, we can easily iterate through the array, array list, or any collection. As the name suggests, we can traverse through every element in an array or collection. This technique was introduced from Java5.

Usage of Enhanced for loop

We can use enhanced for loop to iterate elements for the below collection:

  • Array
  • ArrayList
  • Map
  • Set
  • LinkedList and so on.

Advantages of ForEach loop

  • Easy to retrieve every element in an array or collection
  • Code is more readable
  • Does not work on any condition or boolean expression
  • Less possibility of bugs or errors.

Disadvantages of ForEach loop

  • Cannot retrieve elements based on an index
  • It is not possible to traverse in reverse order
  • Cannot modify array element values

Syntax of ForEach loop

for(datatype variable: arrname or collectionname) {
    //code
}

datatype – datatype of the array or collection list

variable – loop variable

arrname or collectionname – the variable name of array or collection

Java ForEach loop in Array

public class EnhancedForLoopDemo {

  public static void main(String[] args) {
    String[] lang = {"Java","C","C++","PHP","VBScript","Javascript"};
    for(String names: lang) {
      System.out.println(names);
    }	
  }

}
Java
C
C++
PHP
VBScript
Javascript

In this example, we use java for each loop to traverse through an array of string values. Hence for every iteration, the loop variable names hold an array element.

Java ForEach loop in ArrayList

Below is an example of iterating through an ArrayList of integers using a java for-each loop and then calculating the sum of all numbers. First, we declare an ArrayList of integers and then add elements to it. Since it is an ArrayList of integer we should use int datatype within the loop.

import java.util.ArrayList;

public class ForEachArrayList {

  public static void main(String[] args) {
    ArrayList<Integer> numbers = new ArrayList<Integer>();
    numbers.add(56);
    numbers.add(100);
    numbers.add(30);
    numbers.add(45);
    int sum=0;
    for(int num:numbers) {
      System.out.println(num);
      sum=sum+num;
    }
    System.out.println("Sum of numbers:" + sum);
  }

}
56
100
30
45
Sum of numbers:231

Java ForEach loop in Set

We can also use Java for-each loop to retrieve Set elements. In this example, we have created a HashSet of String and then added elements to it. Inside the loop, we declare a String variable strnames which is the loop variable, and then iterate over each element in the Set names.

import java.util.*;

public class SetArray {

  public static void main(String[] args) {
    Set<String> names = new HashSet<String>();
    names.add("Roshan");
    names.add("Kiran");
    names.add("Tejas");
    names.add("Karthik");
    
    for(String strnames:names) {
      System.out.println(strnames);
    }

  }

}
Roshan
Kiran
Tejas
Karthik

Java ForEach loop in Map

Below is an example of using a for-each loop in Map. HashMap contains key-value pairs. We have declared a HashMap with String and Integer pair and added elements to the Map strData. In a map, we have 3 different options to retrieve elements from a Map.

Retrieve Key data alone:

In the first for-each loop, we are retrieving only key data. Since key data is of type string, we have used String variable inside for loop and used keyset() method to get the keys alone.

Retrieve Value data alone:

In the second for-each loop, we retrieve value alone. For this, we use integer variable inside for loop since the value is of integer type and use values() method to get values.

Retrieve key-value data:

In the third for-each loop, we get both key-value pairs.

import java.util.HashMap;

public class ForEachMap {

  public static void main(String[] args) {
    HashMap<String,Integer> strData = new HashMap<>();
    strData.put("Dev", 100);
    strData.put("Harish", 101);
    strData.put("Alok", 102);
    strData.put("Praveen", 103);
    
    System.out.println("Names:");
    for(String names:strData.keySet()) {
      System.out.println(names);
    }
    
    System.out.println("\nID:");
    for(int id:strData.values()) {
      System.out.println(id);
    }

    System.out.println("\nHash Map Data with Names and ID:");
    for(String strValues:strData.keySet()) {
      System.out.println(strValues + " " + strData.get(strValues));
    }
  }

}
Names:
Dev
Alok
Harish
Praveen

ID:
100
102
101
103

Hash Map Data with Names and ID:
Dev 100
Alok 102
Harish 101
Praveen 103

To understand more about maps, please refer to the Java HashMap tutorial.

Java ForEach loop in LinkedList

The below example shows you how to iterate through a linked list using Enhanced for loop.

import java.util.LinkedList;

public class ForEachLinkedList {

  public static void main(String[] args) {
    LinkedList<String> list = new LinkedList<>();
    list.add("Chennai");
    list.add("Delhi");
    list.add("Bangalore");
    list.add("Hyderabad");
    
    for(String cities: list) {
      System.out.println(cities);
    }
  }

}
Chennai
Delhi
Bangalore
Hyderabad

Nested ForEach loop

Similar to normal for loop, we can also have nested for each loop. Let’s understand this with an example below.

We have a 2-dimensional integer array of values assigned to variable arrNumbers. In the first for-each loop, we declare a 1-dimensional array variable oneArray. This means oneArray will have 2 sets of values [12,14,16] and [11,13,15] and has 2 iterations. Within this, we use nested for-each to retrieve individual array elements of each 1-dimensional array. In other words, the outer for-each loop will have 2 iterations and the inner for-each loop will have 3 iterations. In this way, we can get an array of 2-dimensional elements using a for-each loop.

public class NestedForEach {

  public static void main(String[] args) {
    int[][] arrNumbers = {{12,14,16},{11,13,15}};
    for(int[] oneArray : arrNumbers) {
      for(int i: oneArray) {
        System.out.print(i+",");
      }
      System.out.println();
    }

  }

}
12,14,16,
11,13,15,

Difference between For loop and ForEach loop in Java

In the previous tutorial, we have learned about for loop. The below table shows the major differences between for loop and enhanced for loop.

For LoopFor-each loop
Executes based on the condition mentioned within for loopDoes not have any condition specified
We can specify the increment or decrement counter variable.It automatically increments by 1 and we cannot specify the same
We can access array elements based on index valueWe cannot access elements based on index value
Able to iterate forward and reverse directionAble to iterate only in forward direction
Available from JDK 1 onwardsAvailable from JDK 5 onwards
Can be used for any type like integer,strings, collection, arrayCan be used only for array and collection type.

Reference

Translate »