How to Iterate over a List in Java How to Iterate over a List in Java

Page content

In this tutorial, we’ll learn different ways to iterate over a list in Java.

Let’s print list of prime numbers using basic and enhanced for loop

List<Integer> primeNumbers = Arrays.asList(1, 2, 3, 5, 7);
		
// basic for loop
for(int i = 0; i < primeNumbers.size(); i++) {
  System.out.println(primeNumbers.get(i));
}

// enhanced for loop
for (Integer number : primeNumbers) {
    System.out.println(number); 
}

Java 8 introduced forEach method to loop through a List which is very convenient and easy to use.

List<Integer> primeNumbers = Arrays.asList(1, 2, 3, 5, 7);

// Iterable.forEach with lambda expression
primeNumbers.forEach(number -> System.out.println(number));

// Iterable.forEach with method reference ::
primeNumbers.forEach(System.out::println);

// Stream.forEach with lambda expression
primeNumbers.stream().forEach(number -> System.out.println(number));

// Stream.forEach with method reference ::
primeNumbers.stream().forEach(System.out::println);

Iterator is used to iterate over the list in forward direction.

  • hasNext() Returns true if the iteration has more elements.
  • next() Returns the next element in the iteration.
List<Integer> primeNumbers = Arrays.asList(1, 2, 3, 5, 7);

Iterator<Integer> iterator = primeNumbers.iterator();
		 
while(iterator.hasNext()) {
    System.out.println(iterator.next()); 
}

ListIterator is an iterator for lists that allows the programmer to traverse the list in either direction (forward or backward), and obtain the iterator’s current position in the list.

  • hasNext() returns true if this list iterator has more elements when traversing the list in the forward direction.
  • next() returns the next element in the list and advances the cursor position.
  • hasPrevious() returns true if this list iterator has more elements when traversing the list in the reverse direction.
  • previous() returns the previous element in the list and moves the cursor position backwards.
List<Integer> primeNumbers = Arrays.asList(1, 2, 3, 5, 7);
		
ListIterator<Integer> listIterator = primeNumbers.listIterator();

// iterate forward
while(listIterator.hasNext()) {
    System.out.println(listIterator.next());
}

// iterate backward
while(listIterator.hasPrevious()) {
    System.out.println(listIterator.previous());
}