How to loop through a list in Java

In this post we will provide an example of how to loop through a list in Java. Examples will include using the new Java 1.8 forEach method, the older version of forEach and an iterator so that you can loop through a list.

How to loop through a list in Java

Example 1:

The first example is using the new forEach() method in Java 8 and it makes looping through a list a lot more concise and simple.

Example 2:

The following example is assuming you are on a previous version of Java( above Java 5 and below Java 8). As you can see the syntax is slightly different but not too complex.

Example 3:

The final example uses the iterator which allows you to remove elements whilst you iterator through the list. Attempting to remove an element with the previous examples will result in a java.util.ConcurrentModificationException exception being thrown.

Running any of the above examples produces the following output:

I hope the above has given you an idea on how to loop through a list.

Similar posts:

  1. How to loop through a Map in Java
  2. Convert a List to a Set
  3. Example of how to use CountDownLatch in Java
  4. Java 8 Stream allMatch, noneMatch and anyMatch examples

References:

  1. Java 8 List API Documentation

Leave a Reply