×

How to Iterate List in Java?

List is a Collection foundation interface in Java. It enables us to keep the collection of objects in order. The four classes that make up the List interface implementation are ArrayList, LinkedList, Stack, and Vector. In Java, the ArrayList and LinkedList are frequently utilised. We will discover how to iterate a List in Java in this part. This section will use ArrayList only.

Java for Loop

  • Basic for Loop and Enhanced for Loop

Java Iterators

  • Iterator and ListIterator

Java for Loop

Basic for Loop

The most popular flow control loop for iteration is the Java for loop. A variable that functions as an index number is present in the for loop. It runs till the entire List has finished iterating.

Syntax:

for (initialization ; condition ; increment or decrement)  
{  
// code to be iterated 
}

Iterate1.java

import java.util.*;  
// importing all the required packages
public class Iterate1  
{  
public static void main (String args[])   
{  
// initializing a list name  
List<String> name = Arrays.asList ("kmm", "hyd", "delhi", "nsp", "mdk", "nij");  
// iterating over the list name using the for loop 
for (int x = 0; x < name.size(); x++)   
{  
// Displaying the list elements using the get method of list  
System.out.println( name.get(i) );  
}  
}  
}  

Output:

kmm 
hyd
delhi
nsp
mdk
nij

Improved for Loop

It resembles the fundamental for loop. It is readable, simple, and small. It is frequently used to traverse the List. In contrast to a simple for loop, it is simple.

Syntax:

for ( data_type obj : array or collection)  
{    
// code to be iterated  
}     

Iterate2.java

// importing all the required packages 
import java.util.*;  
public class Iterate2  
{  
public static void main (String args[])   
{  
// initializing a list name    
List<String> name = Arrays.asList("kmm", "hyd", "delhi", "nsp", "mdk", "nij");  
// iterating over the list name using the enhanced for loop  
for (String obj : name)   
{  
// Displaying the list elements using the obj     
System.out.println( obj );   
}  
}  
}  

Output :

kmm 
hyd
delhi
nsp
mdk
nij

An iterator in Java

Java offers an interface Iterator for iterating through Collections, including List, Map, and other types. We may iterate through the List by using its two essential methods next() and hasNaxt().

next(): The iteration is carried out in forward order using this method. It gives back the following element in the list. If the iteration doesn't include the List's subsequent element, a NoSuchElementException is thrown. This function can be used in conjunction with previous(): to travel back and forth or repeatedly to iterate through the list.

hasNext(): The hasNext() method enables us to locate the List's final entry. It determines if the next element is present in the List or not. The hasNext() method returns true if it encounters the element while traversing in the forward direction; otherwise, it returns false and ends the execution.

Iterate3.java

// importing all the required packages
import java.util.*;  
public class Iterate3  
{  
public static void main (String args[])   
{  
// initializing a list name      
List<String> name = Arrays.asList("kmm", "hyd", "delhi", "nsp", "mdk", "nij");   
// creating an object for iterator class to iterate over list.
Iterator<String> itr = name.iterator();  
// iterating over the object till the last using while loop
While (itr.hasNext())   
{  
// Displaying the list elements using the obj     
System.out.println( itr.next() );   
}  
}  
}  

Output :

kmm 
hyd
delhi
nsp
mdk
nij

ListIterator

Another interface in the java.util package is the ListIterator. The IteratorE> interface is extended. We can go over the List iteratively in either forward or backward order. The identical mechanism that the Iterator uses is provided by the forward iteration over the List. To iterate through the List, we use the next() and hasNext() methods of the Iterator interface.

Iterate4.java

// importing all the required packages
import java.util.*;  
public class Iterate4  
{  
public static void main (String args[])   
{  
// initializing a list name      
List<String> name = Arrays.asList("kmm", "hyd", "delhi", "nsp", "mdk", "nij");    
// creating an object for ListIterator class to iterate over list.
ListIterator<String> obj = name.listIterator();  
// iterating over the object till the last using while loop
while ( obj.hasNext() )   
{  
// Displaying the list elements using the obj       
System.out.println( obj.next() );  
}  
}  
}   

Output :

kmm 
hyd
delhi
nsp
mdk
nij

Related Topics

Java File

Java file class implements the concept of file handling. It has several methods, such as deleting, creating, reading, and updating files. This class allows java users to perform various operations...

5 minutes read.

Java DatagramSocket and Java DatagramPacket

Datagrams TCP/IP style networking specifies a serialized, predictable, and reliable stream of data in the form of a packet. Servers and clients communicate through a reliable channel, such as TCP socket, have a dedicated...

6 minutes read.

Bottom view of a binary tree in Java

The lowest nodes in their horizontal distance are present and referred to as the bottom view of a binary tree. The horizontal distance between the nodes of a binary tree...

4 minutes read.

Java Math floorDiv() Method

The floorDiv () method of Math class returns the largest integer value that is less than or equal to the algebraic quotient. It firstly divides the dividend and divisor and...

2 minutes read.

Check whether Java is installed or not

As we know that there are various operating systems, to check whether Java is installed or not in Windows and Mac we use the following ways.           Windows Operating System: There are several...

2 minutes read.

Java vs Scala

Java : Java is an object oriented programming language. It is also known as multi threaded language. It was designed by James gosling in the year 1995. We can also say...

4 minutes read.

Java Math.multiplyExact() method

In java, we are provided with multiplyExact method in the Math module. This Math module belongs to the java.lang package. In general, this method returns the product of the provided...

2 minutes read.

Bounded buffer problem in Java

The Bounded buffer Problem can also be called a Producer consumer problem. The problem covers two processes—the producer and the consumer—that share a single, fixed-size buffer that serves as a...

4 minutes read.

What is new in Java 17?

Java 17 LTS is the most recent long-term support release for the Java SE platform. Under the Oracle No-Fee Terms and Conditions License, which stands for long-term support, JDK 17...

6 minutes read.

Statements in java

What is Statement in java: A statement in java is an instruction that explains what will happen based on the condition. Types of java statements: There are different statements in java Expression statementDeclaration statementControl...

2 minutes read.

Java Snippets

The term "snippet" refers to a section of code that addresses numerous issues with just a few lines of code. Decreases the number of lines of code and improves programmer...

3 minutes read.

Interface Program in Java

Interface Program in Java In the previous topic, we discussed that abstraction is possible through the interface and abstract class. An abstract class provides partial to 100% abstraction. 100 %abstraction in...

4 minutes read.

Java Garbage Collection Interview Questions

One of the key areas of Java is garbage collection. Garbage collection enables apps to manage memory automatically. Interviewers frequently ask inquiries about garbage collection. Q1: What is the purpose of...

6 minutes read.

Java Math nextUp() Method

The nextUp() method of Math class returns the floating-point number adjacent to the argument in direction of the positive infinity. Syntax: public static double nextUp (double d)public static float nextUp (float f) Parameters: The...

2 minutes read.

Highest precedence in Java

In Java, the operator is the first thing that springs to mind when discussing precedence. The order in which the operators in an expression are evaluated is controlled by a...

3 minutes read.

Java List Implementations

ArrayList and LinkedList are the two implementations of List that are for general-purpose. You'll probably utilise an array list the majority of the time because it's quick and provides constant-time...

3 minutes read.

Math fma () method in java

In java, the Math module constitutes of fma () Method in it. This method can be accessed in two ways which can be differentiated by the parameters which are given...

4 minutes read.

How to Solve the Deprecated Error in Java?

Deprecated Java methods should not be used because they are deprecated (often, there are better, more modern alternatives). API update. Until now, Java has kept everything backward compatible and never...

3 minutes read.

Stack Program in Java

Stack Program in Java The Stack class is part of the collection framework that inherits the Vector class. Thus, the Stack class can also be called a subclass of the Vector...

5 minutes read.

Generics vs Wildcard in Java

In generic programming, the question mark (?) is often referred to as the wildcard. It stands for a mysterious type. The wildcard can be used for many different contexts, such as...

4 minutes read.