In this post, we will discuss various methods to iterate over a List in Java.
1. Using List.toString()
If we simply want to display contents of the list, we can do that by converting list to a string using toString()
function and then simply printing it as shown below:
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import java.util.List; import java.util.ArrayList; import java.util.stream.Stream; class ListUtil { // Java program to print an ArrayList public static void main (String[] args) { List<String> list = new ArrayList<String>(); list.add("C"); list.add("C++"); list.add("Java"); // 1. Print string representation of the list using toString() System.out.println(list.toString()); // 2. Java 8 way! Stream.of(list.toString()) .forEach(System.out::println); } } |
2. Using ListIterator or Iterator
The List
interface provides a special iterator, called a ListIterator, that allows bidirectional access in addition to the normal operations that the Iterator
interface provides. We can call List.listIterator() to get a ListIterator
over the elements in a list. We can also use List.iterator()
that returns an Iterator
.
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
import java.util.ArrayList; import java.util.List; import java.util.Iterator; import java.util.ListIterator; import java.util.Arrays; class ListUtil { // Java Program to iterate over a List public static void main (String[] args) { List<String> list = Arrays.asList("C", "C++", "Java"); // 1. Using ListIterator to iterate over a List ListIterator<String> lItr = list.listIterator(); // hasNext() returns true if the list has more elements while (lItr.hasNext()) { // next() returns the next element in the iteration System.out.println(lItr.next()); } // 2. Using Iterator Iterator<String> itr = list.iterator(); while (itr.hasNext()) { System.out.println(itr.next()); } } } |
Generic
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.ListIterator; class ListUtil { // Generic code to iterate over a List in Java public static <T, C> void IterateUsingIterator(List<T> list, Class<C> iteratorClass) { if (iteratorClass.getSimpleName().equals("ListIterator")) { // using ListIterator to iterate over a List ListIterator<T> lItr = list.listIterator(); while (lItr.hasNext()) { System.out.println(lItr.next()); } } else if (iteratorClass.getSimpleName().equals("Iterator")) { // using Iterator to iterate over a List Iterator<T> itr = list.iterator(); while (itr.hasNext()) { System.out.println(itr.next()); } } } // Java Program to iterate over a List public static void main (String[] args) { List<String> list = Arrays.asList("C", "C++", "Java"); // 1. print list using ListIterator IterateUsingIterator(list, ListIterator.class); // 2. print list using Iterator IterateUsingIterator(list, Iterator.class); } } |
3. Using for loop / enhanced for loop:
We know that List is an ordered collection, so we can access elements by their index in the list using a for loop.
The for loop also has another form designed for iteration through Collections and arrays called enhanced for loop. We can also use enhanced for to loop through the list.
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
import java.util.List; import java.util.ArrayList; import java.util.Arrays; class ListUtil { // Java Program to iterate over a List public static void main (String[] args) { List<String> list = Arrays.asList("C", "C++", "Java"); // 1. print list using for loop for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i)); } // 2. print list using enhanced for loop for (String s : list) { System.out.println(s); } } } |
4. Java 8 – using Streams and Lambda
In Java 8, we can loop a List with the help of streams, lambdas and forEach. Below program shows 4 ways to do that –
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
import java.util.Arrays; import java.util.List; import java.util.stream.Stream; class ListUtil { // Java Program to iterate over a List public static void main (String[] args) { List<String> list = Arrays.asList("C", "C++", "Java"); // 1. get stream and use lambda expression list.stream().forEach(S -> { System.out.println(S); }); // shorthand for above code list.stream().forEach(S -> System.out.println(S)); // 2. by providing method reference list.stream().forEach(System.out::println); // 3. list inherit forEach() from Iterable interface list.forEach(System.out::println); // 4. using Stream.of() to get Stream<String> Stream.of(list.toArray()) .forEach(System.out::println); } } |
5. Converting List to Array
We can also convert the list to an array using List.toArray(T[ ]) method and then iterating over the array using a for loop or print it using Arrays.toString()
. There are several other implementations of toArray()
method as shown below:
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
import com.google.common.collect.FluentIterable; import com.google.common.collect.Iterables; import java.util.Arrays; import java.util.List; class ListUtil { // Java Program to iterate over a List public static void main (String[] args) { List<String> list = Arrays.asList("C", "C++", "Java"); // Convert list to array String[] array = null; // 1. using List.toArray(T[]) method array = list.toArray(new String[list.size()]); System.out.println(Arrays.toString(array)); // 2. List.toArray(T[]) - without allocating any memory array = list.toArray(new String[0]); System.out.println(Arrays.toString(array)); // 3. using List.toArray() method System.out.println(Arrays.toString(list.toArray())); // 4. Java 8 - Streams + method references array = list.stream().toArray(String[]::new); System.out.println(Arrays.toString(array)); // 5. Java 8 - Streams + lambda expressions array = list.stream().toArray(n -> new String[n]); System.out.println(Arrays.toString(array)); // 6. using FluentIterable class from Guava Library array = FluentIterable.from(list).toArray(String.class); System.out.println(Arrays.toString(array)); // 7. using Iterables class from Guava Library array = Iterables.toArray(list, String.class); System.out.println(Arrays.toString(array)); } } |
6. Using Enumeration Interface
Finally, we can make use of deprecated Enumeration interface to print a list. This interface provides methods to enumerate through the elements of a vector. So, we need to convert our list to Vector first and then print all elements of that Vector.
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
import java.util.*; class ListUtil { // Java Program to iterate over a List public static void main (String[] args) { List<String> list = Arrays.asList("C", "C++", "Java"); // 1. Converting List to Vector @Deprecated Enumeration<String> enumeration = new Vector(list).elements(); // if enumeration contains more elements while (enumeration.hasMoreElements()) { // print next element of the enumeration System.out.println(enumeration.nextElement()); } // 2. Collections.enumeration() returns an enumeration over the // specified collection enumeration = Collections.enumeration(list); while (enumeration.hasMoreElements()) { System.out.println(enumeration.nextElement()); } } } |
Related Post: Iterate List in Reverse Order
Thanks for reading.
Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂
Leave a Reply