Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is ListIterator in Java
3.
Syntax of ListIterator in Java
4.
For example:
4.1.
Java
5.
What is Java List Iterator?
6.
ListIterator is a bi-directional iterator. For this functionality, it has two kinds of methods:
6.1.
1. Forward Direction Iteration:
6.2.
2. Backward Direction Iteration:
7.
Implemenation of ListIterator
7.1.
1. Forward Direction Iteration
7.1.1.
Example:
7.2.
Java
7.3.
2. Backward Direction Iteration
7.3.1.
Example: 
7.4.
Java
8.
ArrayList listIterator() Method in Java
9.
Examples of ArrayList listIterator() Method in Java
9.1.
Example 1: 
9.2.
Java
9.3.
Example 2:
9.4.
Java
10.
LinkedList listIterator() Method in Java
10.1.
Syntax 
10.2.
Parameter
10.3.
Return value
10.4.
Java
11.
Advantages and Disadvantages of Java List Iterator
11.1.
Advantages:
11.2.
Disadvantages:
12.
Iterator v/s ListIterator
13.
Differences Between Iterator and ListIterator
14.
Similarities between Iterator and ListIterator
15.
Frequently Asked Questions
15.1.
How to iterate list in Java 11?
15.2.
What is the significance of ListIterator?
15.3.
When to use list Iterator in Java?
15.4.
Which iterator can be used only with list?
15.5.
Why do we use list Iterator in Java?
16.
Conclusion
Last Updated: Aug 30, 2024
Medium

ListIterator Method in Java

Author Aashna Luthra
0 upvote

Introduction

Java ListIterator is an Interface to iterate over a List in both directions, allowing element modification and index-based operations. In this article, we will discuss what Java ListIterator method is, its implementation, and its advantages and disadvantages. We will also discuss some must-read frequently asked questions for a better understanding of Java ListIterator Method.

java list iterator

What is ListIterator in Java

List Iterator is a sub-interface of the Iterator that can be used to iterator over the elements of the lists. By using List Iterator, Traversal can be done bi-directional (reverse or forward direction). This Iteration can be done to perform the operations such as searching, inserting, deleting, and accessing the elements. You can create an iterator object by calling the iterator() method present in the Collection interface.

Syntax of ListIterator in Java

Iterator itr = CollectionObject.iterator();
Methods in Iterator:

  • hasNext(): If an element exists in the list, the function hasNext() returns true.
  • next(): The function next() returns the list's next entry.
  • remove(): The remove() function removes the last element that the Iterator returns.

For example:

  • Java

Java

import java.util.ArrayList;
import java.util.Iterator;

public class Main{
public static void main(String[] args){

/*Create an ArrayList class object with object of integer type */
ArrayList<Integer> arr = new ArrayList<Integer>();

/* Iterate or traverse over the list */
for (int i = 0; i < 10; i++)
arr.add(i);
System.out.println(arr);

/* The cursor, itr, will initially point to index just before the first element in arraylist */
Iterator<Integer> itr = arr.iterator();

/* Iterating till the boolean hasNext() method returns true and print the next element by iterating the list */
while (itr.hasNext()) {
/* cursor moves to the next element */
int next = itr.next();
System.out.print(next + " ");
}
}
}

Output:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
0 1 2 3 4 5 6 7 8 9 

Explanation
The iterator ‘itr’ initially points to the index just before the first element in arraylist. We iterate till the boolean hasNext() method returns true and we print the next element by iterating the list.

What is Java List Iterator?

ListIterator is a Java iterator that can be used to iterate across ArrayList, Vector, LinkedList, Stack, and other list types. It has been available since Java 1.2. The Listiterator extends the iterator interface and allows for both forward and backward traversal or bi-directional traversal. It supports - Create, Read, Update, and Delete, which are all four CRUD operations.

There are some functionalities that Java List Iterator provides for better implementation, such as Bidirectional Iteration, Indexed-based Acess, Element Modification, Efficient Manipulation, and Supported List Implementation. We can have more control over iteration on elements if we use List Iterator. While using List Iterator, we should take care of some exceptions that can occur, like ConcurrentModificationException, NoSuchElementException, IllegalStateException, and UnsupportedOperationException.

ListIterator is a bi-directional iterator. For this functionality, it has two kinds of methods:

  • Forward Direction Iteration
  • Backward Direction Iteration

1. Forward Direction Iteration:

  • hasNext(): If an element exists in the list, the function hasNext() returns true.
  • next(): The function next() returns the list's next entry.
  • nextIndex(): The nextIndex() function returns the element's index that will be returned by the next() method.

2. Backward Direction Iteration:

  • hasPrevious(): When the list has more elements to traverse in the backward direction than in the forward way, the hasPrevious() method returns true.
  • previous(): The function previous() retrieves the list's previous entry.
  • previousIndex(): the element's index that the previous() method would return is returned by the previousIndex() function.
Backward Direction Iteration

You may refer to the Iterator vs ListIterator to know more about the difference between Iterator and ListIterator. 

Implemenation of ListIterator

1. Forward Direction Iteration

In this Iteration, elements are moved and assessed in the forward direction.

Functions used in Forward Direction Iteration :

  • hasNext(): If the list contains elements in the forward direction, it returns true.
  • next(): It returns the next element of the list.
  • next index(): It returns the index of next element after calling the next().

Example:

  • Java

Java

import java.util.*;
public class CodingNinjas {
public static void main(String[] args) {

List<String> words = new LinkedList<>();
words.add("I");
words.add("AM");
words.add("CODER");
ListIterator<String> listIterator = words.listIterator();
System.out.println(listIterator.nextIndex());
while (listIterator.hasNext()) {
System.out.println(listIterator.next());
}
}
}

Output: 

0
I
AM
CODER

2. Backward Direction Iteration

In this Iteration, elements are moved and assessed in the backward direction.

Functions used in Backward Direction Iteration :

  • hasPrevious(): If the list contains elements in the backward direction, it returns true.
  • previous(): It returns the previous element of the list.
  • previous index(): It returns the previous index returned by the previous() function.

Example: 

  • Java

Java

import java.util.*;
public class CodingNinjas {
public static void main(String[] args) {
List<String> words = new LinkedList<>();
words.add("I");
words.add("AM");
words.add("CODER");
ListIterator<String> listIterator = words.listIterator();
while (listIterator.hasNext()) {
listIterator.next();
}
System.out.println(listIterator.previousIndex());
while (listIterator.hasPrevious()) {
System.out.println(listIterator.previous());
}
}
}

Output

2
CODER
AM
I

ArrayList listIterator() Method in Java

The Java ArrayList's listIterator () method returns an iterator across the list's elements beginning at the specified position. The first element that would be returned by next() is given by the specified index. When previous() is first called, it returns the element at the specified index minus one.

Syntax: 

public ListIterator<E> listIterator(int index);

Parameter: When calling the iterator.next() method, "index" refers to the index of the first element that will be returned from the list iterator. 

Return value: By starting at the specified position in the list, this method returns a list iterator across the elements in the list (in the correct order).

Exception: The iterator throws IndexOutOfBoundsException if the index is out of range, i.e., index < 0 or index > size of the list.

Examples of ArrayList listIterator() Method in Java

Let’s see examples describing iteration methods of the ListIterator interface in an array list.

Example 1

  • Java

Java

import java.util.ArrayList;
import java.util.ListIterator;

class Main {
   public static void main(String[] args) {
       
       /*Creating an ArrayList */
       ArrayList<Integer> arr = new ArrayList<>();
       arr.add(10);
       arr.add(11);
       arr.add(12);
       arr.add(13);
       arr.add(14);
       arr.add(15);
       
       System.out.println("Print ArrayList: " + arr);

       /*Create an instance ‘iter’ of ListIterator */
       ListIterator<Integer> iter = arr.listIterator();

       int nextNumber = iter.next();
       System.out.println("Next Element is: " + nextNumber );

       int nextIndex = iter.nextIndex();
       System.out.println("Index of Next Element: " + nextIndex );

       boolean hasNext = iter.hasNext();
       System.out.println("Does the array have any next element? " + hasNext);

       iter.next();
       iter.next();
       iter.next();
       iter.next();

       int prevNumber = iter.previous();
       System.out.println("Previous Element is: " + prevNumber );

       int prevIndex = iter.previousIndex();
       System.out.println("Index of Previous Element: " + prevIndex );

       boolean hasPrev = iter.hasPrevious();
       System.out.println("Does the array have any previous element? " + hasPrev);
   }
}


Output: 

ArrayList listIterator() Method in Java


Explanation

Initially, the cursor lies before the first element of the array list. After calling the next() method, the iterator instance will be between 10 and 11 and thus 10 is printed as the next element. The index is thus printed as 1. Since the array list contains elements ahead of the next() method, thus the boolean hasNext() returns true. Now, the next() method has been called 4 times. Thus now the instance of the iterator method will be between 14 and 15. Thus previous() returns 14 and so the index is returned as 3. Since the array list contains elements before the iterator instance, the boolean hasPrevious() returns true. 

Example 2:

  • Java

Java

import java.util.ArrayList;
import java.util.ListIterator;


class Main {
   public static void main(String[] args) {
       
       /*Creating an ArrayList */
       ArrayList<Integer> arr = new ArrayList<>();
       arr.add(10);
       arr.add(11);
       arr.add(12);
       arr.add(13);
       arr.add(14);
       arr.add(15);
       
       System.out.println("Print ArrayList: " + arr);

       /* Create an instance ‘iter’ of ListIterator */
       ListIterator<Integer> iter1 = arr.listIterator(6);

       boolean hasNext = iter1.hasNext();
       System.out.println("Does the array have any next element? " + hasNext);
       iter1 = arr.listIterator(7);
   }
}


Output:

output3

Try it on java online compiler.

Explanation

The instance “iter” is positioned at the index 6 of the array list, which is the last index of the list. The boolean hasNext() will return false as there is no next element in the array. The iterator “iter1” throws IndexOutOfBoundsException error since it is trying to access the index which exceeds the array size.

LinkedList listIterator() Method in Java

The Java.util.LinkedList.listIterator() method returns a list iterator with the same elements as the LinkedList and in the same order beginning at a particular location or index number as the LinkedList. The function receives the position or index as a parameter.

Syntax 

ListIterator new_list = LinkedList.listIterator(int index);

Parameter

When calling the iterator.next() method, "index" refers to the index of the first element that will be returned from the list iterator. 

Return value

By starting at the specified position in the list, this method returns a list iterator across the elements in the list (in the correct order).

Let’s see an example to see the working linkedlist listIterator().

  • Java

Java

import java.util.LinkedList;
import java.util.ListIterator;

public class Main {
   public static void main(String args[]) {
       
       /*Creating a demo list */
       LinkedList<Integer> list = new LinkedList<Integer>();

       /*Using add() method to add elements in the list */
       list.add(10);
       list.add(11);
       list.add(12);
       list.add(13);
       list.add(14);
       list.add(15);

       /*Display the linkedlist */
       System.out.println("LinkedList items:" + list);
        
       /*Setting the ListIterator at a specified index */
       ListIterator iter = list.listIterator(3);

       /* Iterating through the new list from the position */
       System.out.println("The list using listIterator is as follows:");
       
       while(iter.hasNext()){
          System.out.println(iter.next());
       }
   }
}


Output:

LinkedList listIterator() Method in Java


Explanation

The iterator “iter” is positioned on specified index 3 of the list, which means the cursor now points to the index 3. Now we iterate the list till the boolean hasNext() holds true. Thus, the output is given as 13 14 15, since the iter starts from index 3 of the list.

Advantages and Disadvantages of Java List Iterator

Advantages:

  • The four CRUD operations—Create, Read, Update, and Delete—are supported.
  • It allows forward and backward iteration in both directions or bi-directional traversal.
  • Using simple method names is simple.

Disadvantages:

  • This iterator supports only list implementation classes.
  • All collection APIs are not covered by it.
  • The list Iterator does not allow for element iteration in parallel.

Iterator v/s ListIterator

Iterator and ListIterator are the Interfaces in Java that are used to iterate the elements in the collection or the list. 

Iterator is an interface in Java that provides a way to iterate the elements in the collection. There are some methods, such as hasNext(), next(), and remove(), that can be used while doing an iteration using the Iterator interface.

ListIterator is a sub-interface of Iterator that extends the functionality of Iterator to iterate the elements in the list as well. There is support for bi-directional (forward or backward) iteration while using ListIterator. There are some methods, such as hasPrevious(), previous(), and nextIndex(), that can be used while doing an iteration using the ListIterator interface.

Differences Between Iterator and ListIterator

ParametersIteratorListIterator
Iteration Direction Iteration can be done in only a forward direction.Iteration can be done bidirectional (forward or backward direction)
Accessing Previous ElementsIterator methods are very limited and can not access the previous elements in the collection.ListIterator provides additional methods such as hasPrevious(), previous(), and previousIndex() that can be used to access the previous elements and indexes.
Modification & InsertionIterator provides the method remove() for the removal.ListIterator provides the methods set(E element) and add(E element) for the modification and insertion in the list.
Initial Position While IteratingIn Iterator, the initial position while iterating is before the first element.In ListIterator, the initial position while iterating is between the first and second elements.

Similarities between Iterator and ListIterator

  • Iterator and ListIterator can be used to iterate the elements in the collection.
  • To check the next element in the collection, Iterator and ListIterator can use the hasNext() method.
  • To check the previous element in the collection, Iterator and ListIterator can use the hasPrevious() method.
  • To remove the element, Iterator and ListIterator can use the remove() method.

Frequently Asked Questions

How to iterate list in Java 11?

There are some methods by which the list can be iterated:

  • Enhanced for loop can be used: for(Integer num: list)
  • for loop with the indexing can be used: for(int i = 0; i < list.size(); i++)
  • The iterator interface can be used: Iterator<Integer> iterator = list.iterator()

What is the significance of ListIterator?

ListIterator is a Java interface that enables you to traverse a List in both forward and backward directions, as well as make changes to the List while iterating. It has more functionality than a regular Iterator and is helpful for performing complex List manipulations.

When to use list Iterator in Java?

ListIterator is useful when you need to modify the list during the time of iteration, like inserting or removing at specific positions and when the traversal of the list in both forward and backward directions is being done.

Which iterator can be used only with list?

The ListIterator interface can be used only with Lists, as it provides methods to traverse a List bidirectionally and perform modifications to the List during iteration.

Why do we use list Iterator in Java?

We use a list iterator in Java to traverse and manipulate elements in a list. It's like a guided tour through a list, allowing us to move forward and backward, remove items, or add new ones easily.

Conclusion

In this article, we explored the Java list iterator. We explored examples related to the Java list iterator and how it works with array list and linked list. We also studied its pros and cons. We believe this article on Java list iterator was helpful. To learn more about Java Iterators, check out our articles on


Refer to our guided paths on Code360 to learn more about DSA, System Design, Competitive Programming, JavaScript, etc. Enroll in our courses and refer to the problems available and mock tests. Take a look at the interview bundle and interview experiences for placement preparations.

Live masterclass