In this article, we will learn about the different ways in which you can iterate over a List in Java.
- Using a while loop
- Using a for loop
- Using a for-each loop
- Using Iterator
- Using ListIterator
- Using forEach method
Using a while loop
A while loop can be used to iterate over a List. However, in this case, an explicit loop control variable needs to be used. This needs to be initialized outside the loop and incremented in each iteration of the loop.
Sample Code
List<Integer> numbers = Arrays.asList(26,1,8,11,37); int count = 0; while(count < numbers.size()) { int num = numbers.get(count); System.out.println(num); count++; }
- Line 1 declares and initializes an Integer List called numbers
- Line 2 declares a loop control variable called count which is initialized to 0
- Lines 3-7 specify a while loop that iterates as long as the loop control variable, that is count is less than the number of elements in the List.
- Lines 5-6 retrieve the current element in the List and simply print it
- Line 7 increments the loop control variable
Output
Using a for loop
A for loop can also be used to iterate over a List. As seen earlier, a while loop requires an explicit loop control variable to be initialized before the loop body and incremented in each iteration of the loop. The for loop does away with all this and thus requires less lines of code than a while loop.
Sample Code
List<Integer> numbers = Arrays.asList(26,1,8,11,37); for(int i=0;i &lt; numbers.size();i++) { int num = numbers.get(i); System.out.println(num); }
- As before, Line 1 declares and initializes an Integer List called numbers
- Lines 2-5 specify a for loop that iterates from 0 till the number of elements in the loop
- In the case, the loop control variable that is i, the condition to be checked (i < numbers.size()) and iteration statement (i++) is specified in the for statement itself
- Thus, the body of the for loop (Lines 3-4) simply retrieves the next element from the List and print it.
- This code produces the same output as before
Using the for-each loop
The for-each loop further simplifies iterating over a List. It automatically retrieves the next element in the List and assigns it to a variable. Thus, there is no need to write code to fetch the next element in the List. The body of the loop is repeated as long as there are elements in the List.
Sample Code
List<Integer> numbers = Arrays.asList(26,1,8,11,37); for(int num:numbers) { System.out.println(num); }
- Lines 2-4 specify a for each loop. In this case, there is no loop control variable, condition, and iteration statement specified.
- In each iteration of the loop, the next element from the numbers List is fetched and assigned to the variable num.
- Thus, the body of the loop (Line 3) is repeated for each element in numbers and the loop is automatically terminated once all the elements from the numbers List are exhausted.
Using Iterator
Iterator is an interface in the Collection framework. It can be used to iterate over any collection. The java.util.Iterable interface has a method called iterator which returns an Iterator instance. Since Iterable is the root of all the collection interfaces, the iterator method is available to all the Collection interfaces. Thus, when the iterator method is invoked on a List, it returns an Iterator instance that can be used to iterate over the List.
Sample Code
List<Integer> numbers = Arrays.asList(26,1,8,11,37); Iterator<Integer> itr = numbers.iterator(); while(itr.hasNext()) { System.out.println(itr.next()); }
- Line 2 invokes the iterator method on numbers. This returns an Iterator of type Integer which can be used to iterate over numbers
- Lines 3-5 specify a while loop. Iterator has a method called hasNext which returns a boolean value indicating whether there are more elements in the collection or not. This is checked in the while condition and if true the loop is entered
- The Iterator interface also has a method called next which returns the next element in the List. Line 4 uses this method to prints the current element in the List.
Using ListIterator
The Iterator interface has a sub-interface called ListIterator. This can also be used to iterate over a List. While the Iterator interface can be used to iterate only in the forward direction, the ListIterator can be used to iterate in both, the forward and backward direction. Secondly, an Iterator cannot be used to modify an element in the List while a ListIterator can be used to modify a List element.
Sample Code
List<Integer> numbers = Arrays.asList(26,1,8,11,37); ListIterato<Integer> itr = numbers.listIterator(); System.out.println("Iterating in forward direction:"); while(itr.hasNext()) { System.out.println(itr.next()); } System.out.println("Iterating in backward direction:"); while(itr.hasPrevious()) { System.out.println(itr.previous()); }
- Line 2 invokes the listIterator method on numbers. This returns a ListIterator of type Integer which can be used to iterate over numbers
- Lines 4-6 specify a while loop which iterates over the List in the forward direction just like an Iterator
- In addition, the ListIterator has methods hasPrevious and previous which can be used to iterate over the List in the backward direction.
- Lines 8-9 specify a while loop that iterates in the backward direction.
Using forEach Method
forEach is a new method that is added to the java.util.Iterable interface by Java 8. As mentioned earlier, Iterable is the root of all the collection interfaces, so the forEach method is also available to all the Collection interfaces. The forEach method accepts as a parameter a Consumer instance. Consumer is an in-built functional interface that can be implemented via a lambda expression. The forEach method simply applies the lambda expression to every element in the collection. This method of iterating over a List is very concise since it does not require an explicit loop. It is also known as internal iteration.
Sample Code
List<Integer> numbers = Arrays.asList(26,1,8,11,37); numbers.forEach(num -> System.out.println(num));
- Lines 2 invokes the forEach method on numbers. A lambda expression is specified which accepts as a parameter a value and simply prints it.
- The forEach method applies the lambda expression to every element in the numbers List.
Conclusion
So, in this article, we saw the different ways of iterating over a List. We first saw how to use them while, for, and for-each loops to iterate over a List. We then saw how to use the Iterator, ListIterator, and the forEach method to iterate over a List.