Iterate through List Java example shows how to iterate over a List using for loop, enhanced for loop, Iterator, ListIterator, while loop and Java 8 forEach.
How to iterate through List in Java?
Let’s first create a List object and add some elements to it.
1 2 3 4 5 6 7 8 9 |
//create a new List List<Employee> employeeList = new ArrayList<Employee>(); //add employee objects to the list employeeList.add( new Employee("E01", "Raj", "IT") ); employeeList.add( new Employee("E02", "Jason", "Marketing") ); employeeList.add( new Employee("E03", "Robert", "Supply Chain") ); employeeList.add( new Employee("E04", "Vicky", "Logistics") ); employeeList.add( new Employee("E05", "Rita", "IT") ); |
We have added several Employee objects to our ArrayList.
There are several ways you can iterate over a List or List implementations like the LinkedList or an ArrayList as given below.
1) Iterate through List using an Iterator
You can get the Iterator object from the list using the iterator
method to iterate over a list as given below.
1 2 3 4 5 |
//get Iterator using iterator method of the List Iterator<Employee> itrEmployees = employeeList.iterator(); while( itrEmployees.hasNext() ) System.out.println( itrEmployees.next() ); |
2) Using the ListIterator
You can get the ListIterator object from the List object using the listIterator
method of List to iterate as given below.
1 2 3 4 5 |
//get ListIterator using listIterator method of the List ListIterator<Employee> listItrEmployees = employeeList.listIterator(); while( listItrEmployees.hasNext() ) System.out.println( listItrEmployees.next() ); |
3) Using a for loop
This is the simplest approach of all. You can use a for loop and loop from index 0 to the size of the list – 1 and access the list elements as given below.
1 2 3 |
for(int i = 0; i < employeeList.size(); i++){ System.out.println( employeeList.get(i) ); } |
4) Using enhanced for loop
For Java 1.5 version and above, you can use enhanced for loop as well.
1 2 3 |
for(Employee emp : employeeList){ System.out.println( emp ); } |
5) Using while loop
You can even use a while loop to access the list elements. Maintain the list index in a separate variable and increment it each time you access the list as given below.
1 2 3 4 5 6 7 |
int listIndex = 0; while( listIndex < employeeList.size() ){ System.out.println( employeeList.get(listIndex) ); //increment list index by 1 listIndex++; } |
6) Using Java 8 forEach
If you are using Java 8 or a later version, you can use the forEach construct to iterate.
1 |
employeeList.forEach( employee -> System.out.println(employee) ); |
See Also:
This example is a part of the Java ArrayList tutorial.
Please let me know your views in the comments section below.