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

Generate Parenthesis | Intuition + Code | Recursion Tree | Backtracking | Java

Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…

2 months ago

Square Root of Integer

Given an integer A. Compute and return the square root of A. If A is…

1 year ago

Build Array From Permutation

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…

1 year ago

DSA: Heap

A heap is a specialized tree-based data structure that satisfies the heap property. It is…

1 year ago

DSA: Trie

What is a Trie in DSA? A trie, often known as a prefix tree, is…

1 year ago

Trees: Lowest Common Ancestor

What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…

1 year ago