The solution is simple

final int[] numbers = new int[] {2,4,6,8,10,12,14,16,18,20};
final List<Integer> list = new ArrayList<Integer>();
for (int number : numbers) {
    list.add(number);
}
Answer from nucandrei on Stack Overflow
🌐
Reddit
reddit.com › r/learnjava › for-each loop arraylist
r/learnjava on Reddit: For-each loop ArrayList
April 4, 2023 -

I am in the third part of a MOOC course on Java. And I'm a little confused about the ambiguity of using the For-each loop to enumerate a list.

Consider the following list as an example

ArrayList<Integer> list = new ArrayList<>();

The examples and answers present two implementations:

for (Integer val: list) {

//do something

}

for (int val: list) {

//do something

}

But it is not explained how one differs from the other and when one or the other variant should be used. Please tell me the difference between the two.

Top answer
1 of 3
13
Java has something called autoboxing and unboxing . Integer is an object. int is a primitive type. An Integer object can be unboxed into a int. And an int can be autoboxed into a Integer. In the examples above the List contains Integer objects. The difference is: In the first, val is a reference to the Integer object in the List. In the second, val is a primitive value that was unboxed from the Integer object in the List.
2 of 3
1
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full - best also formatted as code block You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit/markdown editor: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
🌐
W3Schools
w3schools.com › java › ref_arraylist_foreach.asp
Java ArrayList forEach() Method
if else else if Short Hand If...Else Nested If Logical Operators Real-Life Examples Code Challenge Java Switch ... For Loop Nested Loops For-Each Loop Real-Life Examples Code Challenge Java Break/Continue Java Arrays
Discussions

How to fill out an ArrayList with for each loop? (Java) - Stack Overflow
I have to fill in an ArrayList with the first 10 multiples of two using a for each loop. I really can't seem to figure out how and I can't use any other loops. Here is my code which is not working... More on stackoverflow.com
🌐 stackoverflow.com
For-each loop ArrayList
Java has something called autoboxing and unboxing . Integer is an object. int is a primitive type. An Integer object can be unboxed into a int. And an int can be autoboxed into a Integer. In the examples above the List contains Integer objects. The difference is: In the first, val is a reference to the Integer object in the List. In the second, val is a primitive value that was unboxed from the Integer object in the List. More on reddit.com
🌐 r/learnjava
6
11
April 4, 2023
How does foreach Loop work in arraylist since the 'i' in for each loop is primitive
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/javahelp
5
2
August 24, 2022
TIL that traditional for loop works 3x times faster on Arraylist in comparison to for-each. Why?
Beware, this might be because iterating an ArrayList is so fast anyway that the difference between going through the indirection of having an iterator vs accessing the ArrayList directly (which is array backed) is significant. But that also means that whatever you do inside the loop will probably take much more. And this also means that you shouldn't rush to remove all for-each loops in a premature optimization that might be totally unnecessary. More on reddit.com
🌐 r/androiddev
31
27
August 15, 2018
🌐
Runestone Academy
runestone.academy › ns › books › published › csawesome › Unit7-ArrayList › topic-7-3-arraylist-loops.html
7.3. Traversing ArrayLists with Loops — CSAwesome v1
For this method, you will need a loop that goes through the ArrayList allPairs and for each WordPair in allPairs, it checks to see if its first word (using the getFirst method) equals the second word (using the getSecond method). If there is a match, it increments a counter which it returns at the end of the method.
🌐
Programiz
programiz.com › java-programming › library › arraylist › foreach
Java ArrayList forEach()
We can use the Java for-each loop to iterate through each element of the arraylist.
🌐
GeeksforGeeks
geeksforgeeks.org › java › for-each-loop-in-java
For-Each Loop in Java - GeeksforGeeks
3 weeks ago - Example 2: Iterating in a List using for-each loop ... import java.util.*; class Geeks { public static void main(String[] args) { List<Integer> list = new ArrayList<>(); list.add(3); list.add(5); list.add(7); list.add(9); int max = Integer.MIN_VALUE; for (int num : list) { if (num > max) { max = num; } } System.out.println("List of Integers: " + list); System.out.println("Maximum element: " + max); } }
🌐
GeeksforGeeks
geeksforgeeks.org › java › arraylist-foreach-method-in-java
ArrayList forEach() Method in Java - GeeksforGeeks
July 11, 2025 - In Java, the ArrayList.forEach() method is used to iterate over each element of an ArrayList and perform certain operations for each element in ArrayList. Example 1: Here, we will use the forEach() method to print all elements of an ArrayList ...
Find elsewhere
🌐
Codecademy
codecademy.com › docs › java › arraylist › .foreach()
Java | ArrayList | .forEach() | Codecademy
April 13, 2025 - The .forEach() method performs a specified action on each element of the ArrayList one by one. This method is part of the Java Collections Framework and was introduced in Java 8 as part of the Iterable interface, which ArrayList implements.
🌐
BeginnersBook
beginnersbook.com › 2013 › 12 › how-to-loop-arraylist-in-java
How to loop ArrayList in Java
The enhanced for loop provides a simple and more readable way to iterate through all the elements in an ArrayList. Let’s take the same example that we have seen above but with for-each loop instead of for loop. import java.util.ArrayList; public class ArrayListExample { public static void main(String[] args) { ArrayList<String> names = new ArrayList<>(); names.add("Chaitanya"); names.add("Rahul"); names.add("Aditya"); for (String name : names) { System.out.println(name); } } }
🌐
Coderanch
coderanch.com › t › 613169 › java › forEach-loop-display-output-multiple
Can you use c:forEach loop to display output of multiple arrays or arraylists? (JSP forum at Coderanch)
When I needed to get 100's of data to get from 14 arraylists from databases, I simply used The same if I used c:forEach is like this... See I have used 2 forEach loops for 2 different arraylists... arraylist names are same as in first example..I stored them in request object. I want to folow java programming conventions which states to use minimum possible or no scriplets in jsp pages...
🌐
Coderanch
coderanch.com › t › 673429 › java › iterate-Object-ArrayList
How to iterate through Object ArrayList? (Java in General forum at Coderanch)
December 2, 2016 - If you don't specify a toString() method yourself in the class, the toString() method that class UserData inherits from class java.lang.Object is called, which prints something like "UserData@7f0c871e". So, you have to implement your own toString() method in class UserData, which returns a ...
🌐
Programiz
programiz.com › java-programming › enhanced-for-loop
Java for-each Loop (With Examples)
In Java, the for-each loop is used to iterate through elements of arrays and collections (like ArrayList).
🌐
IONOS
ionos.com › digital guide › websites › web development › java for-each loop
How to use for-each loops in Java - IONOS
November 3, 2023 - The for-each loop is used in many scenarios where Java de­vel­op­ers need to work with arrays. For example, a common use is to output or search for specific elements of an array. The for-each loop can likewise be used to iterate through elements in a list im­ple­ment­ed as an ArrayList.
🌐
How to do in Java
howtodoinjava.com › home › collections framework › java arraylist › java arraylist foreach()
Java ArrayList forEach() with Examples - HowToDoInJava
January 12, 2023 - ArrayList forEach() method iterate the list and performs the argument action for each element of the list until all elements have been processed.
🌐
CodeGym
codegym.cc › java blog › loops in java › for each loop in java
For Each Loop in Java
December 26, 2024 - A for-each is a kind of for loop that you use when you need to process all the elements of an array or collection. That said, the phrase for-each is not actually used in this loop.
🌐
W3Schools
w3schools.com › java › java_arraylist.asp
Java ArrayList
How Tos Add Two Numbers Swap Two ... Number ArrayList Loop HashMap Loop Loop Through an Enum ... assert abstract boolean break byte case catch char class continue default do double else enum exports extends final finally float for if implements import instanceof int interface long module native new package private protected public return requires short static super switch synchronized this throw throws transient try var void volatile while Java String ...
🌐
Quora
quora.com › How-do-I-output-a-loop-to-a-list-or-array-in-Java
How to output a loop to a list or array in Java - Quora
Answer (1 of 4): I see no reason this would make sense. A loop is a sequence of code that repeats over and over. Why would you want to output those instructions to a list or an array? Perhaps you meant to ask, “How can I use a loop to compute a set of values which I will store in a list or array...
🌐
Quora
quora.com › How-do-I-display-all-the-elements-in-ArrayList-in-Java-using-loop
How to display all the elements in ArrayList in Java using loop - Quora
Answer (1 of 12): We can display all the elements in ArrayList in Java using : 1. By use of for loop 2. By use of enhanced for loop 3. By use of lambda expression 4. By use of method reference 5. By use of stream Let’s see in example: [code]import java.util.ArrayList; import java.util.Arrays; ...
🌐
Medium
medium.com › @YodgorbekKomilo › day-12-for-each-loop-arraylist-in-java-7802d97b799c
Day 12 — For-each Loop & ArrayList in Java | by Yodgorbek Komilov | Medium
December 24, 2025 - When you want to iterate over elements ... loop. for (datatype variable : arrayOrCollection) { // code to execute for each element } int[] numbers = {10, 20, 30, 40, 50}; for (int num : numbers) { System.out.println(num); } ... No need ...
🌐
Sentry
sentry.io › sentry answers › java › java for-each loops
Java for-each loops | Sentry
December 15, 2023 - This allows us to use the same for-each loop syntax for both arrays and iterables. import java.util.ArrayList; import java.util.List; import java.util.Arrays; class Main { public static void main(String[] args) { List<String> productsList = new ArrayList<>(); productsList.add("Coffee"); productsList.add("Tea"); productsList.add("Chocolate Bar"); String[] productsArray = new String[]{"Coffee", "Tea", "Chocolate Bar"}; for (String product : productsList) { System.out.println(product); } for (String product : productsArray) { System.out.println(product); } // both for loops will produce the same output } } Note that the iteration variable in a for-each loop merely contains a copy of the value at that point in the list and reassigning it will not change the underlying list.