Flat Preloader Icon

Java for-Each loop

  • In Java, the for-Each loop is used to iterate over elements in a collection. It was introduced in Java 8 as part of the Java Stream API and is available for collections that implement the Iterable interface, such as lists, sets, and maps. It simplifies the process of iterating through elements and performing an action for each element in the collection.

Here Is A Simple Example Of Using The For-each Loop With An ArrayList

				
					import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        // Create an ArrayList of Strings
        ArrayList<String> list = new ArrayList<>();
        list.add("Apple");
        list.add("Banana");
        list.add("Cherry");
        list.add("Date");

        // Using forEach to iterate over the elements
        list.forEach(item -> System.out.println(item));
    }
}

				
			
  • In this example, we have created an ArrayList of Strings and added some elements to it. We then used the for-Each method to iterate over each element of the list and print it to the console. The lambda expression item -> System.out.println(item) is the action performed on each element during iteration.

for-Each() Signature In Iterable Interface

				
					default void forEach(Consumer<super T>action)  
				
			

Java 8 for-Each() example 1

				
					import java.util.ArrayList;  
import java.util.List;  
public class ForEachExample {  
    public static void main(String[] args) {  
        List<String> gamesList = new ArrayList<String>();  
        gamesList.add("Football");  
        gamesList.add("Cricket");  
        gamesList.add("Chess");  
        gamesList.add("Hocky");  
        System.out.println
        ("------------Iterating by passing lambda 
        expression--------------");  
        gamesList.forEach(games -> 
        System.out.println(games));  
          
    }  
}  
				
			

Output

				
					----Iterating by passing lambda expression----
Football
Cricket
Chess
Hocky