Simpler way to do it...

ArrayList<MyObject> list = ...
for( MyObject obj : list)
  obj.count()
Answer from raffian on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › java › iterating-arraylists-java
Iterating over ArrayLists in Java - GeeksforGeeks
Now it is a further additive to the article as we are done with discussing all methods that can be used to iterate over elements. Till now we have traversed over input elements only and have not seen the traversal what if we play with elements, so do we are considering ... import java.util.List; import java.util.ArrayList; import java.util.Iterator; public class GFG { public static void main(String[] args) { // Creating a List with referenceto ArrayList List<Integer> al = new ArrayList<Integer>(); al.add(10); al.add(20); al.add(30); al.add(1); al.add(2); // Remove elements smaller than 10 using // Iterator.remove() Iterator itr = al.iterator(); while (itr.hasNext()) { int x = (Integer)itr.next(); if (x < 10) itr.remove(); } System.out.println("Modified ArrayList : " + al); } }
Published   January 19, 2026
Discussions

Iterating through an arrayList of objects
Well an array list is like an array except it's endless. An array can ONLY hold a limited amount of items you tell it to whereas an array list can hold as many items and constantly grows to hold more items. With that said, you can get stuff from (for example): for (int I = 0; I < arraylist.size(); I++) { if (arraylist.get(i).getId() == 1) { sysout("found!"); } } when you say arraylist.get(i), it's an Employee object- meaning it has all the employee methods (accessors/mutators aka getters/setters). Using an enhanced for each loop is the same thing except no need to say arraylist.get(i) anymore since emp is the same as arraylist.get(i) More on reddit.com
🌐 r/javahelp
6
1
November 7, 2018
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 do you efficiently loop through a linkedlist?
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
14
12
February 5, 2022
Why does the List interface have forEach, but not map?
why isn't every List a Stream? To answer this part of the question, it's because a stream is a fundamentally different datatype than a list. A list represents a collection of data, while a stream represents a pipeline for processing data. Streams can only be processed once, and are designed to perform multiple operations on some provided data. They don't store any intermediate results, and then do lazy processing once you specify a terminal operator (like toList() or forEach()). For example, if you had something like this: Stream a = List.of(1, 2, 3).stream(); Stream b = a.filter(n -> n > 1); Stream c = b.map(n -> String.valueOf(n)); List d = c.toList(); This is functionally identical to this: List d = List.of(1, 2, 3).stream() .filter(n -> n > 1) .map(n -> String.valueOf(n)) .toList(); If you inspected b, however, it would not contain any data about what elements were remaining, because the stream has not executed yet. Assigning the various steps of the stream along the way doesn't actually DO anything to the data, it just creates pointers to instances of the pipeline. As mentioned before, the pipeline can only be executed once, which means a stream is consumed when you perform a terminal operation on it. It also can't be executed if you chain it to another pipeline. If, in the example above, you tried to do b.toList(), you'd get an IllegalStateException, because b was already operated on. If you did c.toList(), you'd get a list of "2", "3". If you did c.toList() a second time, you'd once again get an IllegalStateExcecution, because c has already been consumed. The intermediate operators like map actually do nothing except modify the pipeline definition until you call toList at the end. Once you execute toList, then the pipeline operates in a lazy way, evaluating the data elements one at a time. So, to recap: List: collection of ordered data Stream: an operation pipeline definition More on reddit.com
🌐 r/java
90
121
October 26, 2024
🌐
W3Schools
w3schools.com › java › java_howto_loop_through_arraylist.asp
Java How To Loop Through an ArrayList
close() delimiter() findInLine() findWithinHorizon() hasNext() hasNextBoolean() hasNextByte() hasNextDouble() hasNextFloat() hasNextInt() hasNextLine() hasNextLong() hasNextShort() locale() next() nextBoolean() nextByte() nextDouble() nextFloat() nextInt() nextLine() nextLong() nextShort() radix() reset() useDelimiter() useLocale() useRadix() Java File Methods Java FileInputStream Java FileOutputStream Java BufferedReader Java BufferedWriter Java Iterator Methods Java Collections Methods Java System Methods Java Errors & Exceptions · Java Examples Java Videos Java Compiler Java Exercises Java
🌐
Reddit
reddit.com › r/javahelp › iterating through an arraylist of objects
r/javahelp on Reddit: Iterating through an arrayList of objects
November 7, 2018 -

Hello! I am trying to iterate through an ArrayList and having trouble with getting my loop right. I am trying to use an advanced for loop (the method I figured would be easier for me to understand) to iterate through an arrayList of objects that is some 60,000 records in a database. Basically I need to ask the user for an employee ID and the program is supposed to search the database for it and if it exist then it prints out the info associated to the ID (last name, first name, birthdate). I have all the code right for the database part but I am stuck on getting the program to print the info. I know I need to create the scanner object, the loop, and then somehow use get methods right? Any help would be appreciated!

Here is some of the code I have if it helps:

public static void main(String\[\] args) {
		ArrayList<Employee> emp = getDBData();
		searchEmployee(emp);	
}
	//Search Employee method...
	private static void searchEmployee(ArrayList<Employee> emp) {	
	}
//My arrayList
ArrayList<Employee> set = new ArrayList<Employee>();
//The loop
Scanner scanner = new Scanner(System. in);
		System.out.println("Enter the Employee ID to search: ");
		String empID = scanner.nextLine();	
		for(Employee emp: set){
System.out.println(empID);
		}
🌐
BeginnersBook
beginnersbook.com › 2013 › 12 › how-to-loop-arraylist-in-java
How to loop ArrayList in Java
One of the easiest way to iterate through an ArrayList is by using 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"); // ...
🌐
Programiz
programiz.com › java-programming › examples › iterate-over-arraylist
Java Program to Iterate over an ArrayList
Here, we have used the for-each loop to iterate over the ArrayList and print each element. import java.util.ArrayList; import java.util.ListIterator; class Main { public static void main(String[] args) { // Creating an ArrayList ArrayList<Integer> numbers = new ArrayList<>(); numbers.add(1); numbers.add(3); numbers.add(2); System.out.println("ArrayList: " + numbers); // Creating an instance of ListIterator ListIterator<Integer> iterate = numbers.listIterator(); System.out.println("Iterating over ArrayList:"); while(iterate.hasNext()) { System.out.print(iterate.next() + ", "); } } }
Find elsewhere
🌐
Learn
learn.java › learning › tutorials › CS14Lists › iterate-over-arraylist
Iterating over an ArrayList - Learn.java
One way to iterate over the elements of an ArrayList is to use a for loop to iterate over the indices of the list.
🌐
Runestone Academy
runestone.academy › ns › books › published › csjava › Unit8-ArrayList › topic-8-3-arraylist-loops.html
8.3. Traversing ArrayLists with Loops — CS Java
Initialize the allPairs list to an empty ArrayList of WordPair objects. Loop through the words array for the first word in the word pair (for loop from index i = 0 to length-1)
🌐
Vultr Docs
docs.vultr.com › java › examples › iterate-over-an-arraylist
Java Program to Iterate over an ArrayList | Vultr Docs
November 25, 2024 - Obtain an iterator from the ArrayList, and use it to iterate through the elements. This method also allows the removal of elements during iteration which is not safely supported by the other looping constructs.
🌐
Blogger
javarevisited.blogspot.com › 2012 › 03 › how-to-loop-arraylist-in-java-code.html
5 Ways to Loop or Iterate over ArrayList in Java?
My question is looping through Iterator on ArrayList is faster than looping ArrayList via for loop ? ... Soya said... Best way to iterate over ArrayList is by using advanced for-each loop added in Java 5.
🌐
How to do in Java
howtodoinjava.com › home › collections framework › java arraylist › different ways to iterate an arraylist
Different Ways to Iterate an ArrayList
January 12, 2023 - ArrayList<String> namesList = new ...println(namesList.get(i)); } Java program to iterate through an ArrayList of objects using for-each loop....
🌐
Coderanch
coderanch.com › t › 673429 › java › iterate-Object-ArrayList
How to iterate through Object ArrayList? (Java in General forum at Coderanch)
This is printed because your class UserData has no overridden toString() method. When you print an object, like this: the toString() method will be called on the UserData object, to convert it to text to be displayed on the console. If you don't specify a toString() method yourself in the class, ...
🌐
Codecademy
codecademy.com › docs › java › arraylist › .iterator()
Java | ArrayList | .iterator() | Codecademy
August 13, 2024 - The .iterator() method is used to iterate over the elements of a collection (such as an ArrayList) one by one. ... Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
🌐
Medium
medium.com › @reetesh043 › how-to-iterate-arraylist-in-java-with-examples-c66be52c8211
How to Iterate ArrayList in Java with Examples | by Reetesh Kumar | Medium
January 7, 2024 - Our primary focus will be on iterating through the list in its original order, but we’ll also touch on the straightforward process of traversing it in reverse. Let’s assume we have a simple banking system with a list of bank accounts. Each bank account has a balance, an account number, and a customer’s name. We will use the different Java features to iterate over this list of bank accounts in various ways. import java.util.ArrayList; import java.util.List; public class BankAccount { private int accountNumber; private String customerName; private double balance; public BankAccount(int acc
🌐
GeeksforGeeks
geeksforgeeks.org › java › iterate-through-list-in-java
Iterate through List in Java - GeeksforGeeks
July 23, 2025 - It provides a way to iterate over elements in a more parallel-friendly manner. A Spliterator can be obtained from various sources, including collections like lists. The forEachRemaining method of Spliterator is used to traverse all remaining elements sequentially. ... // Java Program iterating over a List // using Spliterator import java.util.List; import java.util.Spliterator; public class ListIteration { public static void main(String[] args) { // List of String List<String> myList = List.of("A", "B", "C","D"); // Using Spliterator Spliterator<String> spliterator = myList.spliterator(); spliterator.forEachRemaining(System.out::println); } }
🌐
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.
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › ArrayList.html
ArrayList (Java Platform SE 8 )
April 21, 2026 - List list = Collections.synchronizedList(new ArrayList(...)); The iterators returned by this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException.
🌐
TutorialsPoint
tutorialspoint.com › iterate-through-arraylist-in-java
Iterate through ArrayList in Java
July 28, 2025 - The Java ArrayList iterator() method returns an iterator over the elements in this list in proper sequence. The iterator is fail-fast means after creation of iterator, any structural modification done to arrayList object without using iterator.add()
🌐
Quora
quora.com › What-is-iteration-What-does-it-mean-to-iterate-through-an-array-in-Java
What is iteration? What does it mean to iterate through an array in Java? - Quora
Answer: I’ll preface my answer with this: I am a junior CS STUDENT. I answer questions like this as much for my own benefit as yours, so if there is a bit more succinct or a better answer, I’m sure someone will give it. That said, your question tells me that you’re either new to programming ...
🌐
Baeldung
baeldung.com › home › java › java list › ways to iterate over a list in java
Ways to Iterate Over a List in Java | Baeldung
June 27, 2025 - In this tutorial, we’ll review the different ways to do this in Java. We’ll focus on iterating through the list in order, though going in reverse is simple, too.