×

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 Integer compareTo() method

The compareTo() method of Integer class compares two Integer objects numerically. Syntax public static int compareTo(int anotherInteger) Parameters The parameter ‘anotherInteger’ represents the Integer to be compared. Specified by This method is specified by compareTo in...

2 minutes read.

Java Math cbrt() Method

The cbrt() method of Math class returns the cube root of a double value. Syntax: public static double cbrt(double a) Parameters: The parameter ‘a’ represents the value whose cube root is to be determined. Return...

2 minutes read.

Java String length() method

Java String length() method returns length of the characters in a String. Syntax: public int length() Returns It returns length of the characters Java String length() method example 1          public class JavaStringLengthEx1  ...

1 minute read.

Differences between Lock and Monitor in Java Concurrency

In this tutorial, we will discuss the overview of Lock and Monitor and the differences between them. Introduction Java Concurrency is the ability to perform specific tasks at a time parallelly. The...

4 minutes read.

Java String endsWith() method

Checks whether this String ends with the specified suffix or not. Syntax public boolean endsWith(String Suffix) Parameter Suffix : It takes suffix as a parameter  i.e. Sequence of characters Returns It returns true when the current...

1 minute read.

Java Viva Questions and Answers

Question: Explain Java programming language. Answer: It is a high-level programming language. This programming language is based on the principles of object-oriented programming. Large-scale applications can be developed by using this...

16 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.

Sleep Time in Java

Sleep is amethod in java that is related to thread class and it is a concept of multithreading and is used to stop the execution of the current thread a...

4 minutes read.

Thread Scheduler in java

Scheduling: it is defined as the execution of multiple threads on a single CPU in some order is called scheduling. Preemptive-priority scheduling: This algorithm schedules threads based on their priority relative to other...

11 minutes read.

Best Java IDE

Applications for desktop, workplace, smartphone, and the internet can be created using Java, one of the most popular programming languages. Java will undoubtedly be a popular programming language for so...

5 minutes read.

Java file Writer

File Writer: It is used to write all the data from text files. It inherits the properties from the Output Stream class. It is meant for writing characters. It is meant...

4 minutes read.

Java Integer parseInt() method

The parseInt() method of Java Integer class parses the CharSequence argument as a signed decimal integer. The second parameter parses the string argument as a signed integer in the radix specified...

2 minutes read.

How to initialize string array in Java

In this tutorial, we will learn how the string array is initialized in java. The initialization of string array in the java by using the NEW (it creates the object for...

3 minutes read.

Java Thread Dump Analyzer

Thread: A thread is a PC program that is stacked into the PC's memory and is under execution. It tends to be executed by a processor or a bunch of processors....

15 minutes read.

Difference between String, StringBuffer and StringBuilder in java

What is a string in Java? Strings are a collection of characters that are commonly used in Java programming. Strings are regarded as objects in the Java programming language. “String” is a...

4 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.

Java Applications

The growth in technology is increasing rapidly, so some languages are used for developing them. Java is one such famous programming language which is having numerous applications. The Java Programming...

4 minutes read.

Manachers Algorithm in Java

Here, we'll go over the four scenarios once more in an effort to approach them differently and use the same strategy. The values of (centerRightPosition - currentRightPosition) and LPS length at...

3 minutes read.

How to compare two dates in different format in Java?

We need to compare two dates frequently when coding. Real-world examples include sorting a list of persons by age or keeping track of students' attendance. To compare two dates, we...

7 minutes read.

How to download and install Eclipse in Windows?

Download and Install Eclipse on Windows Eclipse is an open source IDE (Integrated Development Environment) which is used to help the programmers to provide a platform to write and run the...

1 minute read.