Java

How to Iterate over a list in Java

In Java, you can keep an organized collection of items or elements with the help of lists. These lists can also comprise duplicate entries and null elements. Furthermore, users can also iterate the list in Java by utilizing the Java iterator that can be employed to iterate across ArrayList, Vector, LinkedList, Stack, and other list types.

This write-up will explain the different methods for iterating over a list in Java.

How to Iterate over a list in Java?

To iterate over a list in Java, multiple methods can be used, such as “for loop”, “while loop”, “iterator” and many others. To do so, follow the stated instructions.

Method 1: Iterate over a list in Java Using the “for” Loop

To iterate over a list in Java using the “for” loop, first of all, import the Java libraries: “java.util.ArrayList” and “java.util.List”:

import java.util.ArrayList;
import java.util.List;

 
Next, utilize the following Java code where:

    • Create an string type array list in Java with the help of “ArrayList<String>()” constructor.
    • Next, insert the elements in the list with the help of “add()” method.
    • After that, use the “for” loop and specify the condition according to your choice.
    • Lastly, the “System.out.println()” method is utilized for displaying the output on the console:

 

List<String> aList = new ArrayList<String>();
aList.add("one");
aList.add("Two");
aList.add("Three");
aList.add("Four");
 for (String i : aList)
 {
 System.out.println(i);
 }

 

As you can see, with the help of the “for” loop, we have successfully iterated over the created list:

Method 2: Iterate over a list in Java Using the “while” Loop

Similarly, you can also use the “while” loop to iterate over a list in Java. For that purpose, create a new array list and add elements to the list with the help of a defined method. Furthermore, use the while loop by following the listed instructions:

    • First, initialize the integer type of variable and assign a value to it.
    • Next, utilize the “while” loop and add the condition.
    • size()” specifies the size of the list.
    • System.out.println()” returns output on the console:

 

List<String> aList = new ArrayList<String>();
aList.add("Five");
aList.add("Six");
aList.add("Seven");
aList.add("Eight");
int i = 0;
while (i < aList.size()) {
System.out.println(aList.get(i));
i++;
 }

 

Output


That’s all about the iterating over a list in JavaScript

Conclusion

To iterate over a list in Java, there are multiple methods, including “for loop”, “while loop”, iterator, and others can be utilized. To do so, define a list with the help of the ArrayList class constructor and add the elements in the array. Then, use the “for” or “while” loop and display output on the console. This article has explained the method for iterating over a list in Java.

About the author

Hafsa Javed