Iterate List in Java using Loops
Last Updated :
21 Jun, 2021
In this article, we are going to see how to iterate through a List. In Java, a List is an interface of the Collection framework. List can be of various types such as ArrayList, Stack, LinkedList, and Vector. There are various ways to iterate through a java List but here we will only be discussing our traversal using loops only. So, there were standard three traversals available so do three methods do exists but with the introduction of java 8 and streams other methods do arises out. So, all the four methods are discussed below as follows:
Methods:
- For loop Method
- While Method
- For-each loop Method
- For-each loop of java 8
Implementation:
Method 1: Using a for loop
For Loop is the most common flow control loop. For loop uses a variable to iterate through the list.
Example
Java
// Java Program to Iterate List in java
// using for loop
// Importing all input output classes
import java.io.*;
// Importing all utility classes from
// java.util package
import java.util.*;
// Class
class GFG {
// main driver method
public static void main(String[] args)
{
// Creating an ArrayList object
// Declaring object of Integer type
// Custom entries in array
List<Integer> my_list
= Arrays.asList(10, 20, 30, 40, 50);
// Display message
System.out.print("Iterating over ArrayList: ");
// Iteration over ArrayList
// using the for loop
for (int i = 0; i < my_list.size(); i++)
// Print and display the all elements
// in List object
System.out.print(my_list.get(i) + " ");
// new line
System.out.println();
// No, creating a vector of size N
// Custom entry for N = 5
// Custom Integer entries
List<Integer> v = new Vector<Integer>(5);
v.add(10);
v.add(20);
v.add(30);
v.add(40);
v.add(50);
// Display message
System.out.print("Iterating over Vector: ");
// iterating over vector using for loop
for (int i = 0; i < v.size(); i++)
// Print and display vector elements
System.out.print(v.get(i) + " ");
// New Line
System.out.println();
// Creating a stack containing Integer elements
List<Integer> s = new Stack<Integer>();
// Adding integer elements
// Custom input
s.add(10);
s.add(20);
s.add(30);
s.add(40);
s.add(50);
// Display message
System.out.print("Iterating over Stack: ");
// For loop o iterate over elements in stack
for (int i = 0; i < v.size(); i++)
// Print and display all stack elements
System.out.print(s.get(i) + " ");
}
}
OutputIterating over ArrayList: 10 20 30 40 50
Iterating over Vector: 10 20 30 40 50
Iterating over Stack: 10 20 30 40 50
Method 2: Using While loop
Java while loop similar to For loop is a control flow statement that allows code to run repeatedly until a desired condition is met.
Example
Java
// Java Program to iterate over List
// using while loop
// Importing all input output classes
import java.io.*;
// Importing all utility classes from
// java.util package
import java.util.*;
// Class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating an object of List
// Declaring object of Integer type
// Custom Integer entries
List<Integer> my_list
= Arrays.asList(10, 20, 30, 40, 50);
// Display message
System.out.print("Iterating over ArrayList: ");
// Initially loop variable is initialized
// with zero
int i = 0;
// Iterating over List via while loop
// using size() method
while (i < my_list.size()) {
// Print and display all elements
// of an ArrayList
System.out.print(my_list.get(i) + " ");
// Incrementing the counter by unity safter
// one iteration
i++;
}
i = 0;
// New Line
System.out.println();
// Creating a Vector of size N
// Custom value for N = 5
List<Integer> v = new Vector<Integer>(5);
// Adding 5 elements to the above List object
// for vector
// Custom entries
v.add(10);
v.add(20);
v.add(30);
v.add(40);
v.add(50);
// Display message
System.out.print("Iterating over Vector: ");
// Iterating over Vector via while loop
// using the size() method
while (i < v.size()) {
// Print and display all elements of vector
System.out.print(v.get(i) + " ");
// Increment the counter variable
i++;
}
// Counter variable is initially
// initialized with zero
i = 0;
// New Line
System.out.println();
// Creating a Stack by creating another
// list object of Integer type
// Declaring object of Integer type
List<Integer> s = new Stack<Integer>();
// Adding elements to the above stack
// Custom entries
s.add(10);
s.add(20);
s.add(30);
s.add(40);
s.add(50);
// Display message
System.out.print("Iterating over Stack: ");
// Iterating over stack via while loop
// using size method()
while (i < v.size()) {
// Print and display all elements
// of the above stack/ obj created
System.out.print(s.get(i) + " ");
// Increment the counter by unity
i++;
}
}
}
OutputIterating over ArrayList: 10 20 30 40 50
Iterating over Vector: 10 20 30 40 50
Iterating over Stack: 10 20 30 40 50
Method 3: Using for each loop
Syntax:
for (type temp : list_name)
{
statements using temp;
}
Example
Java
/*package whatever //do not write package name here */
import java.io.*;
import java.util.*;
class GFG {
public static void main(String[] args)
{
// creating Arraylist
List<Integer> my_list
= Arrays.asList(10, 20, 30, 40, 50);
System.out.print("Iterating over ArrayList: ");
// For Each Loop for iterating ArrayList
for (Integer i :my_list)
System.out.print(i + " ");
System.out.println();
// creating Vector of size 5
List<Integer> v = new Vector<Integer>(5);
v.add(10);
v.add(20);
v.add(30);
v.add(40);
v.add(50);
System.out.print("Iterating over Vector: ");
// For Each Loop for iterating Vector
for (Integer i : v)
System.out.print(i + " ");
System.out.println();
// creating Stack
List<Integer> s = new Stack<Integer>();
s.add(10);
s.add(20);
s.add(30);
s.add(40);
s.add(50);
System.out.print("Iterating over Stack: ");
// For Each Loop for iterating Stack
for (Integer i : s)
System.out.print(i + " ");
}
}
OutputIterating over ArrayList: 10 20 30 40 50
Iterating over Vector: 10 20 30 40 50
Iterating over Stack: 10 20 30 40 50
Method 4: Using for each loop of Java 8
This method takes a functional interface as a parameter therefore lambda expression can be passed as an argument.
Syntax:
void forEach(Consumer<? super T> action)
Example
Java
// Importing all input output classes
import java.io.*;
// Importing all classes from
// java,util package
import java.util.*;
// Class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating an Arraylist by creating object
// of List and declaring as Integer type
// Custom Integer entries
List<Integer> my_list
= Arrays.asList(10, 20, 30, 40, 50);
// Display message
System.out.print("Iterating over ArrayList: ");
// Traversing over ArrayList
// using for each method Java 8
my_list.forEach(
list -> System.out.print(list + " "));
// New line
System.out.println();
// creating Vector by creating object of
// List and declaring as Integer type
// Vector is of size N
// N = 5 for illustration purposes
List<Integer> v = new Vector<Integer>(5);
// Adding elements to the vector
// Custom Integer elements
v.add(10);
v.add(20);
v.add(30);
v.add(40);
v.add(50);
// Display message
System.out.print("Iterating over Vector: ");
// Traversing the above vector elements
// using for each method Java 8
v.forEach(vector -> System.out.print(vector + " "));
// New line
System.out.println();
// Creating a Stack by creating an object of
// List and declaring it as of Integer type
List<Integer> s = new Stack<Integer>();
// Adding elements to the above stack created
// Custom inputs addition using add() method
s.add(10);
s.add(20);
s.add(30);
s.add(40);
s.add(50);
// Display message
System.out.print("Iterating over Stack: ");
// Print and display all the elements inside stack
// using for each method Java 8
s.forEach(stack -> System.out.print(stack + " "));
}
}
OutputIterating over ArrayList: 10 20 30 40 50
Iterating over Vector: 10 20 30 40 50
Iterating over Stack: 10 20 30 40 50
Similar Reads
Adding List in a PDF using Java
In this article, we will learn how to create a PDF and add a list to that PDF using java. For adding a list in a PDF, we will use the iText library. These are the steps that should be followed to add a list in a PDF using java. 1. Creating a PdfWriter object The PdfWriter class represents the DocWri
3 min read
Iterate a LinkedList in Reverse Order in Java
For traversing a linked list in reverse order we can use Descending Iterator or List Iterator 1. Descending Iterator Syntax: LinkedList<String> linkedlist = new LinkedList<>(); Iterator<String> listIterator = linkedlist.descendingIterator(); Returns: Descending Iterator returns the
2 min read
Java Program to Iterate Vector using Enumeration
The Vector class implements a growable array of objects. It is available in java.util package. It implements the List interface. The Enumeration interface defines the methods by which you can traverse the elements in a collection of objects. Now in order to add elements Vector Syntax: public class V
2 min read
Program to convert List of String to List of Integer in Java
The Java.util.List is a child interface of Collection. It is an ordered collection of objects in which duplicate values can be stored. Since List preserves the insertion order, it allows positional access and insertion of elements. List Interface is implemented by ArrayList, LinkedList, Vector, and
3 min read
Program to convert List of Integer to List of String in Java
The Java.util.List is a child interface of Collection. It is an ordered collection of objects in which duplicate values can be stored. Since List preserves the insertion order, it allows positional access and insertion of elements. List Interface is implemented by ArrayList, LinkedList, Vector and S
3 min read
Get Previous and Next Index using Java ListIterator
The previous index and next index in an ArrayList can be obtained using the methods previousIndex() and nextIndex() respectively of the ListIterator interface. previousIndex() can also return -1 if it at the beginning of the list. Example: Input: list = [2, 3, 6, 8] listiterator is at the beginning
2 min read
How to Iterate HashSet in Java?
HashSet extends AbstractSet and implements the Set interface. It creates a collection that uses a hash table for storage. It stores information by using a mechanism called hashing. In hashing, the informational content of a key is used to determine a unique value, called its hash code.Methods to Ite
3 min read
How to Iterate HashMap in Java?
HashMap is a part of Javaâs collection providing the basic implementation of the Map interface of Java by storing the data in (Key, Value) pairs to access them by an index of another type. One object is listed as a key (index) to another object (value). If you try to insert the duplicate key, it wil
5 min read
How to Iterate over a Queue in Java?
Queue is a concept of Linear Data Structure that follows the concept of FIFO(First In First Out). Queues are majorly used to maintain the order of the elements to which they are added. In this article, we will learn to perform Queue Iteration in Java. Queue Iteration Program in JavaSyntax with Examp
1 min read
Java Program to Iterate LinkedHashSet Elements
The LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked List across all elements. When the iteration order is needed to be maintained this class is used. When iterating through a HashSet the order is unpredictable, while a LinkedHashSet lets us iterate through the elements
3 min read