Java Collections

ListIterator interface in collection

An iterator for lists that allows the programmer to traverse the list in either direction, modify the list during iteration, and obtain the iterator’s current position in the list. A ListIterator has no current element; its cursor position always lies between the element that would be returned by a call to previous() and the element that would be returned by a call to next().

Accessing a Collection
To access, modify or remove any element from any collection we need to first find the element, for which we have to cycle throught the elements of the collection. There are three possible ways to cycle through the elements of any collection.

  • Using Iterator interface
  • Using ListIterator interface
  • Using for-each loop

Accessing elements using Iterator:
Iterator Interface is used to traverse a list in forward direction, enabling you to remove or modify the elements of the collection. Each collection classes provide iterator() method to return an iterator.
The Methods Declared by Iterator:

SN Methods with Description
1 boolean hasNext( )
Returns true if there are more elements. Otherwise, returns false.
2 Object next( )
Returns the next element. Throws NoSuchElementException if there is not a next element.
3 void remove( )
Removes the current element. Throws IllegalStateException if an attempt is made to call remove( ) that is not preceded by a call to next( ).
import java.util.*;
class TestIterator
{
 public static void main(String[] args)
 {
  ArrayList ar = new ArrayList();
  ar.add("dinesh");
  ar.add("anamika");
  ar.add("adesh");
  ar.add("vinesh");

 Iterator it = ar.iterator();     //Declaring Iterator
  while(it.hasNext())
  {  
   System.out.print(it.next()+" ");
  }
 }
}

output:

Accessing element using ListIterator:
ListIterator Interface is used to traverse a list in both forward and backward direction. It is available to only those collections that implement the List Interface.

import java.util.*;
class TestIterator
{
 public static void main(String[] args)
 {
  ArrayList ar = new ArrayList();
  ar.add("dinesh");
  ar.add("anamika");
  ar.add("adesh");
  ar.add("vinesh");

   ListIterator litr = ar.listIterator();
   while(litr.hasNext())                 //In forward direction
   {
     System.out.print(litr.next()+" ");
   }
    System.out.println();
    while(litr.hasPrevious())             //In backward direction
    {
      System.out.print(litr.previous()+" ");
    }
  }
}

Output:


The Methods Declared by ListIterator:

SN Methods with Description
1 void add(Object obj)
Inserts obj into the list in front of the element that will be returned by the next call to next( ).
2 boolean hasNext( )
Returns true if there is a next element. Otherwise, returns false.
3 boolean hasPrevious( )
Returns true if there is a previous element. Otherwise, returns false.
4 Object next( )
Returns the next element. A NoSuchElementException is thrown if there is not a next element.
5 int nextIndex( )
Returns the index of the next element. If there is not a next element, returns the size of the list.
6 Object previous( )
Returns the previous element. A NoSuchElementException is thrown if there is not a previous element.
7 int previousIndex( )
Returns the index of the previous element. If there is not a previous element, returns -1.
8 void remove( )
Removes the current element from the list. An IllegalStateException is thrown if remove( ) is called before next( ) or previous( ) is invoked.
9 void set(Object obj)
Assigns obj to the current element. This is the element last returned by a call to either next( ) or previous( ).

Using for-each loop
for-each version of for loop can also be used for traversing each element of a collection. But this can only be used if we don’t want to modify the contents of a collection and we don’t want any reverse access. 
for-each loop can cycle through any collection of object that implements Iterable interface.

import java.util.*;
class TestIterator
{
 public static void main(String[] args)
 {
    ArrayList ar = new ArrayList();
    ar.add("dinesh");
    ar.add("anamika");
    ar.add("adesh");
    ar.add("vinesh");

     for(Object str : ls)
     {
       System.out.print(str+" ");
     }
  }
}

output:

<<Previous <<   || Index ||   >>Next >>
Previous
Next
Dinesh Rajput

Dinesh Rajput is the chief editor of a website Dineshonjava, a technical blog dedicated to the Spring and Java technologies. It has a series of articles related to Java technologies. Dinesh has been a Spring enthusiast since 2008 and is a Pivotal Certified Spring Professional, an author of a book Spring 5 Design Pattern, and a blogger. He has more than 10 years of experience with different aspects of Spring and Java design and development. His core expertise lies in the latest version of Spring Framework, Spring Boot, Spring Security, creating REST APIs, Microservice Architecture, Reactive Pattern, Spring AOP, Design Patterns, Struts, Hibernate, Web Services, Spring Batch, Cassandra, MongoDB, and Web Application Design and Architecture. He is currently working as a technology manager at a leading product and web development company. He worked as a developer and tech lead at the Bennett, Coleman & Co. Ltd and was the first developer in his previous company, Paytm. Dinesh is passionate about the latest Java technologies and loves to write technical blogs related to it. He is a very active member of the Java and Spring community on different forums. When it comes to the Spring Framework and Java, Dinesh tops the list!

Share
Published by
Dinesh Rajput

Recent Posts

Strategy Design Patterns using Lambda

Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…

2 years ago

Decorator Pattern using Lambda

Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…

2 years ago

Delegating pattern using lambda

Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…

2 years ago

Spring Vs Django- Know The Difference Between The Two

Technology has emerged a lot in the last decade, and now we have artificial intelligence;…

2 years ago

TOP 20 MongoDB INTERVIEW QUESTIONS 2022

Managing a database is becoming increasingly complex now due to the vast amount of data…

2 years ago

Scheduler @Scheduled Annotation Spring Boot

Overview In this article, we will explore Spring Scheduler how we could use it by…

2 years ago