Categories: Java

Java Iterator for Collection Access

You will frequently wish to repeat the collection’s pieces. You might want to show each element, for instance. Using an iterator—an object that implements either the Iterator or the ListIterator interface—is the simplest way to accomplish this.

You can cycle over a collection using an iterator, adding or removing elements as you go. ListIterator is an extension of the Iterator that enables both bidirectional list traversal and element manipulation.

Follow these steps to use an iterator to cycle through a collection’s contents:

  • Call the iterator() method of the collection to get an iterator to the beginning of the collection.
  • Establish a loop that calls hasNext ( ). Keep repeating the loop until hasNext() returns true.
  • Get each element by calling next within the loop().
Methods Declared by Iterator:
Sr.No.Method & Description
1boolean hasNext( )If there are more elements, it returns true. returns false if not.
2Object next( )Returns the next element. If there is no next element, throws a NoSuchElementException.
3void remove( )eliminates the present element. Throws an IllegalStateException if remove() is tried to be called without calling next first ( ).
Methods Declared by ListIterator:
Sr.No.Method & Description
1void add(Object obj)Inserts obj before the element that will be returned by the following call to next in the list ( ).
2boolean hasNext( )Returns true if there is a next element. Otherwise, returns false.
3boolean hasPrevious( )If there is a prior element, the function returns true. Returns false otherwise.
4Object next( )Returns the next element. A NoSuchElementException is thrown if there is not a next element.
5int nextIndex( )returns the next element’s index. Return the list’s length if there is no following element.
6Object previous( )the preceding element is returned. If there isn’t a prior element, a NoSuchElementException is thrown.
7int previousIndex( )returns the previous element’s index. Returns -1 if there isn’t a prior element.
8void remove( )the current element is taken out of the list. If remove() is used before next() or previous(), an IllegalStateException is raised.
9void set(Object obj)Adds obj to the currently selected element. This is the element returned by the most recent call to either next() or previous() ( ).
Example:
import java.util.*;
public class Coderz {

   public static void main(String args[]) {
      // Create an array list
      ArrayList al = new ArrayList();
      
      // add elements to the array list
      al.add("A");
      al.add("E");
      al.add("I");
      al.add("O");
      al.add("U");
    

      // Use iterator to display contents of al
      System.out.print("Original contents of al: ");
      Iterator itr = al.iterator();
      
      while(itr.hasNext()) {
         Object element = itr.next();
         System.out.print(element + " ");
      }
      System.out.println();
      
      // Modify objects being iterated
      ListIterator litr = al.listIterator();
      
      while(litr.hasNext()) {
         Object element = litr.next();
         litr.set(element + "+");
      }
      System.out.print("Modified contents of al: ");
      itr = al.iterator();
      
      while(itr.hasNext()) {
         Object element = itr.next();
         System.out.print(element + " ");
      }
      System.out.println();

      // Now, display the list backwards
      System.out.print("Modified list backwards: ");
      
      while(litr.hasPrevious()) {
         Object element = litr.previous();
         System.out.print(element + " ");
      }
      System.out.println();
   }
}
Output:
Original contents of al: A E I O U 
Modified contents of al: A+ E+ I+ O+ U+ 
Modified list backwards: U+ O+ I+ E+ A+

Note: also read about the Java.util.Collections Class

Follow Me

If you like my post, please follow me to read my latest post on programming and technology.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Share
Published by
Rabecca Fatima

Recent Posts

Select a Random Element from a Stream

You are given a stream of elements that is too large to fit into memory.…

21 hours ago

Estimate π Using Monte Carlo Method

The formula for the area of a circle is given by πr². Use the Monte…

3 weeks ago

Longest Substring with K Distinct Characters

Given an integer k and a string s, write a function to determine the length…

3 weeks ago

Staircase Climbing Ways

There is a staircase with N steps, and you can ascend either 1 step or…

4 weeks ago

Autocomplete System Implementation

Build an autocomplete system that, given a query string s and a set of possible…

4 weeks ago

Job Scheduler Implementation

Design a job scheduler that accepts a function f and an integer n. The scheduler…

4 weeks ago