Collections

Iterate through List in Java Example

Iterate through List Java Example shows how to iterate over a List using various approaches like using for loop, enhanced for loop, Iterator, ListIterator, while loop and using Java 8 forEach.

How to iterate through List in Java?

Let’s first create a List and add some elements to it.

We have added several Employee objects to our List (ArrayList).

There are several ways you can iterate through a List (or List implementations like LinkedList or ArrayList) in Java as given below.

1) Iterate through List using Iterator

You can get Iterator from the list using iterator method and iterate over a list using it as given below.

2) Iterate through List using ListIterator

You can get ListIterator from the List object using listIterator method of List class and iterate over a list as given below.

3) Iterate through List using simple for loop

This is the simplest approach of all. You can use simple for loop and loop till the size of the list and access list elements as given below.

4) Iterate through List using enhanced for loop

For Java 1.5 and above, you can use enhanced for loop to iterate over List.

5) Iterate through List using while loop

You can even use while loop to access the list elements. Maintain list index in separate variable and increment it each time you access the list as given below.

6) Iterate through List using Java 8 forEach

If you are using Java 8, you can use forEach construct to iterate over a List.

See Also:

Please let us know your views in the comments section below.

 

Want to learn quickly?
Try one of the many quizzes. I promise you will not be disappointed.