Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
IntStream forEach() Method in Java
Next article icon

Iterable forEach() Method in Java

Last Updated : 04 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Java, the foreach() method is the default method in the Iterable interface. It provides a simple way to iterate over all elements of an Iterable such as List, Set, etc. using a lambda expression or method reference.

Example 1: This example demonstrates iterating over a List using an Iterator to print each element of the list.

Java
// Java program to demonstrate the working of // forEach() method of Iterable interface  import java.util.ArrayList;  import java.util.Iterator;  import java.util.List;  import java.util.function.Consumer;   public class Geeks {   	public static void main(String[] args)  	{  		List<String> l = new ArrayList<>();  		l.add("New Delhi");  		l.add("New York");  		l.add("Mumbai");  		l.add("London");   		Iterator<String> i = l.iterator();  		while (i.hasNext()) {   			System.out.println(i.next()); 		 		}  	}  }  

Output
New Delhi New York Mumbai London 

Syntax

default void forEach(Consumer<? super T> action)

  • Parameter: The action parameter is a Consumer<? super T> which is a special type of function that takes an item(of type T) and does something with it, but does not return anything. The foreach() method uses this function to apply the action to each item in the Iterable.
  • Return Type: This method does not return any value.
  • Exception: Throws NullPointerException if the input action is null.

Example 2: This example demonstrates using the forEach() method with an anonymous Consumer class to print each element of a List.

Java
// Java program to demonstrate  // forEach() method with anonymous class import java.util.ArrayList;  import java.util.List;  import java.util.function.Consumer;   public class Geeks {   	public static void main(String[] args)  	{  		List<String> data = new ArrayList<>();  		data.add("New Delhi");  		data.add("New York");  		data.add("Mumbai");  		data.add("London");   		data.forEach(new Consumer<String>() {   			@Override 			public void accept(String t)  			{   				System.out.println(t);  			}   		});  	}  }  

Output
New Delhi New York Mumbai London 

Explanation: In the above example, we have created a List of String with 4 elements and then we have iterated over the list using the forEach method. As described earlier forEach method take Consumer object as input, we have created an anonymous inner class implementation of Consumer interface and overrides the accept method. In this example, we have kept the business logic inside the anonymous inner class and we can not reuse it.

Example 3: This example demonstrate the implementation of Consumer interface separately so that we can reuse it. Let’s create a class CityConsumer which implements Consumer interface and overrides its accept method.

Java
// Java program to demonstrate // uisng a custom Consumer implementation(cityConsumer) with // the forEach() method to print each element of a List import java.util.*; import java.util.function.Consumer;  class CityConsumer implements Consumer<String> {      @Override public void accept(String t)     {         System.out.println(t);     } } // Now we can use the CityConsumer // with forEach method by just creating // an object of CityConsumer class as below  public class Geeks {      public static void main(String[] args)     {         List<String> l = new ArrayList<>();         l.add("New Delhi");         l.add("New York");         l.add("Mumbai");         l.add("London");          // create an object of CityConsumer         // and pass it to forEach method         CityConsumer cityConsumer = new CityConsumer();         l.forEach(cityConsumer);     } } 

Output
New Delhi New York Mumbai London 


Next Article
IntStream forEach() Method in Java

G

go2ksr
Improve
Article Tags :
  • Java
  • Java-Functions
Practice Tags :
  • Java

Similar Reads

  • IntStream forEach() method in Java
    The IntStream forEach() method in Java is a terminal operation that performs a given action on each element of the stream. It is commonly used to iterate through primitive int values in a functional style introduced in Java 8. Syntax of IntStream forEach() Methodvoid forEach(IntConsumer action) Para
    3 min read
  • IntStream forEachOrdered() method in Java
    IntStream forEachOrdered(IntConsumer action) performs an action for each element of this stream in encounter order. IntStream forEachOrdered(IntConsumer action) is a terminal operation i.e, it may traverse the stream to produce a result or a side-effect. Syntax : void forEachOrdered(IntConsumer acti
    2 min read
  • Iterator vs Foreach In Java
    Background : Iterator is an interface provided by collection framework to traverse a collection and for a sequential access of items in the collection. // Iterating over collection 'c' using iterator for (Iterator i = c.iterator(); i.hasNext(); ) System.out.println(i.next()); For eachloop is meant f
    4 min read
  • Vector forEach() method in Java
    The forEach() method of Vector is used to perform a given action for every element of the Iterable of Vector until all elements have been Processed by the method or an exception occurs. The operations are performed in the order of iteration if the order is specified by the method. Exceptions thrown
    3 min read
  • JavaTuples fromIterable() method
    The fromIterable() method in org.javatuples is used to instance a tuple in a semantically elegant way, with the values of the iterable, given as parameters. This method can be used for any tuple class object of the javatuples library. It is a static function in each javatuple class and it returns th
    2 min read
  • ArrayDeque iterator() Method in Java
    The Java.util.ArrayDeque.iterator() method is used to return an iterator of the elements of the ArrayDeque. Syntax: Iterator iterate_value = Array_Deque.iterator(); Parameters: The method does not take any parameter. Return Value: The method iterates over the elements of the deque and returns the va
    2 min read
  • ArrayDeque forEach() method in Java
    The forEach() method of ArrayDeque is inherited from interface java.lang.Iterable. The operation is performed in the order of iteration if that order is specified by the method. Method traverses each element of the Iterable of ArrayDeque until all elements have been processed by the method or an exc
    3 min read
  • How to Iterate Any Map in Java?
    In Java, a Map is a data structure that is used to store key-value pairs. Understanding how to iterate over the elements of a map plays a very important role. There are 5 ways to iterate over the elements of a map, and in this article, we are going to discuss all of them. Note: We cannot iterate ove
    5 min read
  • Java HashSet iterator() Method
    The HashSet iterator() method in Java is used to return an iterator that can be used to iterate over the elements in a HashSet. HashSet does not maintain any specific order of its elements, so the elements are returned in random order when iterated over. The iterator() method provides a way to trave
    3 min read
  • ArrayBlockingQueue iterator() Method in Java
    The iterator() method of ArrayBlockingQueue class is used to returns an iterator of the same elements as this queue in a proper sequence. The elements returned from this method contains elements in order from first(head) to last(tail). The returned iterator is weakly consistent. Syntax: public Itera
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences