Tutorial Playlist
191 Lessons1. Introduction to Java
2. What is Java?
3. History of Java
4. Java Tutorial for Beginners
5. How Do Java Programs Work?
6. JDK in Java
7. C++ Vs Java
8. Java vs. Python
9. Java vs. JavaScript
10. From Java Source Code to Executable
11. How to Install Java in Linux
12. How to Install Java in Windows 10
13. Java Hello World Program
14. Structure of Java Program and Java Syntax
15. Operators in Java
16. Java If-else
17. Switch Case In Java
18. Loops in Java
19. Infinite loop in Java
20. For Loop in Java
21. For Each Loop in Java
22. Constructor in Java
23. Constructor Overloading in Java
24. Copy Constructor in Java
25. Default Constructor in Java
26. Parameterized Constructors in Java
27. Constructor Chaining In Java
28. Finalize Method in Java
29. Static Method in Java
30. Equals Method in Java
31. Abstract Method in Java
32. toString() Method in Java
33. Difference between equals method in Java
34. Inheritance in Java
35. Multiple Inheritance in Java
36. Hierarchical Inheritance in Java
37. Java Classes and Objects
38. Scanner Class in java
39. All classes in java are inherited from which class
40. What is Nested Class in Java
41. POJO Class in Java
42. Anonymous Class in Java
43. Final Class in Java
44. Object Class in Java
45. Packages in Java
46. Access Modifiers in Java
47. Static Keyword In Java
48. Final Keyword in Java
49. Checked and Unchecked Exceptions in Java
50. User Defined Exception in Java
51. Error vs. Exception in Java
52. Java Collection
53. Collections in Java
54. Garbage Collection in Java
55. Generics In Java
56. Java Interfaces
57. Functional Interface in Java
58. Marker Interface in Java
59. Streams in Java
60. Byte stream in java
61. File Handling in Java
62. Thread in Java
63. Thread Lifecycle In Java
64. Daemon Thread in Java
65. Thread Priority in Java
66. Deadlock in Java
67. String Pool in Java
68. Java Database Connectivity(JDBC)
69. Design Patterns in Java
70. Functional Programming in Java
71. OOP vs Functional vs Procedural
72. Heap Memory and Stack Memory in Java
73. Applet in Java
74. Java Swing
75. Java Frameworks
76. Hibernate Framework
77. JUnit Testing
78. How to Install Eclipse IDE for Java?
79. Command line arguments in Java
80. Jar file in Java
81. Java Clean Code
82. OOPs Concepts in Java
83. Java OOPs Concepts
84. Overloading vs Overriding in Java
85. Java 8 features
86. String in Java
87. String to int in Java
88. Why String Is Immutable in Java?
89. Primitive Data Types in Java
90. Non-Primitive Data Types in Java
91. This and Super Keyword in Java
92. HashMap in Java
93. Comparable And Comparator in Java
94. Type Casting in Java
95. Arrays Sort in Java with Examples
96. Variable Hiding and Variable Shadowing in Java
97. Enum in Java
98. Substring in Java
99. Pattern Programs in Java
100. Hashcode in Java
101. What is ByteCode in Java?
102. How To Take Input From User in Java
103. GCD of Two Numbers in Java
104. Linked List in Java
105. Arithmetic Operators in Java
106. Conditional Operators in Java
107. Stack and Queue in Java
108. Array Length in Java
109. Number Pattern Program in Java
110. Split in java
111. Map In Java
112. Difference Between Throw and Throws in Java
113. Difference Between Data Hiding and Abstraction
114. HashSet in Java
115. String Length in Java
116. Factorial Using Recursion in Java
117. DateFormat in Java
118. StringBuilder Class in java
119. Instance variables in Java
120. Java List Size
121. Java APIs
122. Reverse an Array in Java
123. StringBuffer and StringBuilder Difference in Java
124. Java Program to Add Two Numbers
125. String to Array in Java
126. Regular Expressions in Java
127. Identifiers in Java
128. Data Structures in Java
129. Set in Java
130. Pass By Value and Call By Reference in Java
131. Try Catch in Java
132. Bubble Sort in Java
133. Caesar Cipher Program in Java
134. Queue in Java
135. Object Creation in Java
136. Multidimensional Array in Java
137. How to Read a File in Java
138. String Comparison in Java
139. Volatile Keyword in Java
140. Control Statements in Java
141. Jagged Array in Java
142. Two-Dimensional Array in Java
143. Java String Format
144. Replace in Java
145. charAt() in Java
146. CompareTo in Java
147. Matrix Multiplication in Java
148. Static Variable in Java
149. Event Handling in Java
150. parseInt in Java
151. Java ArrayList forEach
Now Reading
152. Abstraction in Java
153. String Input in Java
154. Logical Operators in Java
155. instanceof in Java
156. Math Floor in Java
157. Selection Sort Java
158. int to char in Java
159. Stringtokenizer in java
160. Implementing and Manipulating Abs in Java
161. Char array to string in java
162. Convert Double To String In Java
163. Deque in Java
164. Converting a List to an Array in Java
165. The Max function in java
166. Removing whitespace from string in java
167. String arrays in Java
168. Strings in Java Vs Strings in Cpp
169. Sum of digits of a number in Java
170. Art of Graphical User Interfaces
171. Trim in Java
172. RxJava
173. Recursion in Java
174. HashSet Java
175. Difference Between Java and Python
176. Square Root in Java
177. Reverse A String in Java
178. Even Odd Program in Java
179. Fibonacci Series in Java
180. Prime Number Program in Java
181. Java Program to Print Prime Numbers in a Given Range
182. Java Leap Year Program
183. Swapping of Two Numbers in Java
184. LCM of Two Numbers in Java
185. Math.sqrt() Function in Java
186. Area of Triangle in Java
187. Sort a String In Java
188. Factorial Program in Java
189. Javafx
190. Lambda expression in java
191. Setup Java Home and IDE on macOS
Before you understand the Java ArrayList forEach loop, you need to understand the ArrayList. It is a list used to manipulate and store collections of objects. It is a multipurpose paradigm that allows removing, adding, modifying, and retrieving elements within the list. To simplify the iteration process of the ArrayList in Java, we have the concept of the Java ArrayList forEach loop- also called the “enhanced for loop”.
So what does this loop do? As the ArrayList is dynamic and needs a tedious index management system, this loop takes over managing the ArrayList. It offers a concise syntax and enhances code readability. forEach() in Java makes it easier and more efficient to traverse elements in the ArrayList.
By combining the two efficient paradigms of ArrayLists and the forEach loop, developers streamline their code and achieve efficient data processing and manipulation results.
The scope of this tutorial begins with the fundamentals of ArrayLists as a concept. It will dive deep into the forEach loop and its usage in ArrayLists. By the end of this tutorial, readers will have a solid understanding of how to utilize ArrayLists and the forEach loop together through sufficient Java ArrayList forEach example. So let's get started.
The Java ArrayList forEach() method performs iterations over each element in an ArrayList in Java. As each element passes the check, a user-specified/system-specified action is performed. forEach() in Java streamlines the iterations of items through the ArrayList, offering a concise and efficient way to process each element individually.
Here is an example of using the forEach() method of ArrayList in Java:
In the example above, we create an ArrayList called fruits and add some fruit names. Then, we demonstrate two ways to use the forEach() method to iterate over the elements of the list.
The first usage demonstrates the forEach() method with a lambda expression. Inside the lambda expression, we simply print each fruit using System.out.println(fruit).
The second usage demonstrates the forEach() method with a method reference (System.out::println). This syntax is equivalent to using a lambda expression that calls System.out.println() with the current element as the argument.
Code:
import java.util.ArrayList;
public class upGradTutorials {
public static void main(String[] args) {
ArrayList<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
fruits.add("Mango");
// Using forEach() method with lambda expression
System.out.println("Using forEach() method with lambda expression:");
fruits.forEach(fruit -> System.out.println(fruit));
// Using forEach() method with method reference
System.out.println("\nUsing forEach() method with method reference:");
fruits.forEach(System.out::println);
}
}
Here is the syntax for the forEach() method in Java:
void forEach(Consumer<? super E> action)
Let us now break down the syntax and discuss each component.
The forEach() method of ArrayList in Java does not throw any checked exceptions. However, if the action provided in the forEach() method throws an exception, it will be caught and wrapped in a RuntimeException. This means that any unchecked exceptions thrown by the action will be propagated, resulting in a RuntimeException being thrown.
Here is an example to demonstrate this:
We iterate over an ArrayList of integers in this program using the forEach() method. Inside the action provided by the lambda expression, we divide 10 by each number in the list. Since division by zero is not allowed, an ArithmeticException will occur when the number 0 is encountered.
To handle this exception, we wrap the forEach() method call in a try-catch block and catch the ArithmeticException. If an exception occurs within the forEach() method, it will be caught, and the corresponding error message will be printed.
Remember that this exception handling is specific to the action provided within the forEach() method. The forEach() method itself does not throw any checked exceptions, and any exceptions thrown by the action will be wrapped in a RuntimeException if they are unchecked exceptions.
Code:
import java.util.ArrayList;
public class upGradTutorials {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
try {
numbers.forEach(number -> {
System.out.println(10 / number);
});
} catch (ArithmeticException e) {
System.out.println("ArithmeticException occurred: " + e.getMessage());
}
}
}
Here is an example that showcases two different ways of defining actions using lambda expressions and method references within the forEach() method of ArrayList:
In this above example, we have an ArrayList called names that stores some names. We use the forEach() method to iterate over the elements of the list and perform specific actions.
First, we use a lambda expression name -> System.out.println(name) as the action. This lambda expression simply prints each name in the ArrayList to the console.
Next, we demonstrate the usage of a method reference by passing System.out::printlnUpperCase as the action. The printlnUpperCase method is defined in a separate StringUtils class, and it converts a given string to uppercase and prints it. The forEach() method will call this method for each name in the ArrayList, resulting in the uppercase names being printed to the console.
Code:
import java.util.ArrayList;
public class upGradTutorials {
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<>();
names.add("John");
names.add("Alice");
names.add("Bob");
names.add("Emily");
System.out.println("Names:");
names.forEach(name -> System.out.println(name));
// Using method reference
System.out.println("\nNames in uppercase:");
names.forEach(StringUtils::printlnUpperCase);
}
static class StringUtils {
public static void printlnUpperCase(String str) {
System.out.println(str.toUpperCase());
}
}
}
Here is an example of using the forEach() method on an ArrayList that contains a list of numbers:
In the above program, we have an ArrayList called numberLists, which contains two separate lists of numbers.
We create two List<Integer> instances, list1 and list2, and add them to the numberLists ArrayList.
We then use the forEach() method on numberLists to iterate over each list. Within the outer forEach() iteration, we use another forEach() method to iterate over the numbers within each list. We print each number using System.out.print(), followed by a newline character using System.out.println(), to display each list of numbers on a separate line.
Code:
import java.util.ArrayList;
import java.util.List;
public class upGradTutorials {
public static void main(String[] args) {
ArrayList<List<Integer>> numberLists = new ArrayList<>();
List<Integer> list1 = new ArrayList<>();
list1.add(1);
list1.add(2);
list1.add(3);
numberLists.add(list1);
List<Integer> list2 = new ArrayList<>();
list2.add(4);
list2.add(5);
list2.add(6);
numberLists.add(list2);
System.out.println("Numbers in the lists:");
numberLists.forEach(list -> {
list.forEach(number -> System.out.print(number + " "));
System.out.println();
});
}
}
Here is an example below of using the forEach() method on an ArrayList that contains a list of objects:
In this example, we have an ArrayList called personLists, which contains two lists of Person objects.
We create two List<Person> instances, list1 and list2, and add them to the personLists ArrayList.
We then use the forEach() method on personLists to iterate over each list. Within the outer forEach() iteration, we use another forEach() method to iterate over the Person objects within each list. We print each Person object using System.out.println() by relying on the toString() method overridden in the Person class.
Code:
import java.util.ArrayList;
import java.util.List;
public class upGradTutorials {
public static void main(String[] args) {
ArrayList<List<Person>> personLists = new ArrayList<>();
List<Person> list1 = new ArrayList<>();
list1.add(new Person("John", 25));
list1.add(new Person("Alice", 30));
personLists.add(list1);
List<Person> list2 = new ArrayList<>();
list2.add(new Person("Bob", 28));
list2.add(new Person("Emily", 22));
personLists.add(list2);
System.out.println("Persons in the lists:");
personLists.forEach(list -> {
list.forEach(person -> System.out.println(person));
System.out.println();
});
}
}
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
}
The forEach() method provides a concise way to iterate over a collection and perform an action on each element. The forEachOrdered() method guarantees that the elements are processed in the order they appear in the stream.
Both methods offer different advantages depending on your use case. We use forEach() for unordered processing or when the order is not important, and we use forEachOrdered() when we need to maintain the encounter order of the elements.
Here's an example that showcases the forEach() method in Java 8 and the forEachOrdered() method in Java Stream:
In this example, we have a List called fruits containing different fruit names.
First, we demonstrate the usage of the forEach() method available in Java 8. It iterates over the elements of the list using a lambda expression (fruit -> System.out.println(fruit)) and prints each fruit name to the console. The order of the elements is not guaranteed.
Next, we showcase the forEachOrdered() method in the Java Stream API. This method is used on a stream of elements (fruits.stream()) and ensures that the elements are processed in the encounter order. Again, we use a lambda expression to print each fruit name to the console.
Code:
import java.util.ArrayList;
import java.util.List;
public class upGradTutorials {
public static void main(String[] args) {
List<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
fruits.add("Mango");
// Java 8 forEach() method
System.out.println("Using forEach():");
fruits.forEach(fruit -> System.out.println(fruit));
// Java Stream forEachOrdered() method
System.out.println("\nUsing forEachOrdered():");
fruits.stream().forEachOrdered(fruit -> System.out.println(fruit));
}
}
The ArrayList forEach() method in Java provides a convenient and streamlined approach to iterate over elements in an ArrayList. It eliminates manual index management and enhances code readability by offering a concise syntax. With forEach(), you can easily perform actions on each element of the ArrayList, making it ideal for processing data collections.
This method simplifies complex operations and reduces the likelihood of errors with traditional for loops. By utilizing forEach() effectively, you can efficiently manipulate ArrayList elements and achieve greater code efficiency. Embrace this powerful method to enhance your Java programming skills and optimize your data handling capabilities.
1. Why do we use forEach in Java?
It is a concept used to “traverse” the ArrayList or a particular data set. It benefits the code by eliminating all possible bugs and making it more concise, robust, and readable.
2. What is the primary difference between forEach and for loop?
While the forEach loop works inside a specified range or collection of data, the for loop is applicable globally and is not restricted to a specific list or collection elements alone.
3. Can forEach transform elements in an array?
No, the Java forEach array method is primarily used to loop through the elements of the array. To transform them, you can use the MAP() function instead.
PAVAN VADAPALLI
Director of Engineering
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working …Read More
Popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...