Home  >  Article  >  Java  >  Iterator in Java

Iterator in Java

王林
王林Original
2024-08-30 15:11:37315browse

An Iterator is an interface that is used to fetch elements one by one in a collection. It is available in a Java package called Java. util package. The collection API implements the iterator() method, and hence data can be retrieved from interfaces like Map, List, Queue, Deque, and Set, which are all implemented from the collection framework. As the name suggests, an iterator in Java iterates through a collection of objects.

Syntax:

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Iterator<E> iterator()

Below the iterator is the name of an object created by calling iterator() method of collection interface. “collection” is the collection object’s name.

Iterator iter = collection.iterator();

Methods of Iterator in Java

Iterators have 4 methods in Java that are used to traverse through collections and retrieve the required information. They are as follows:

  • hasNext(): This is a method that returns boolean true if the iteration has a next element present and boolean false if there is no element present next.
  • next (): This method returns the element value present in the coming iteration. Suppose no elements are returned in the next iteration, then a “NoSuchElementException” is thrown.
  • remove(): This method removes the present element returned by the iterator from the collection. In case this method is called previous to the next() method, it throws “IllegalStateException.”
  • forEachRemaining(): This method executes all the remaining elements in the collection until they have been processed or until an exception is thrown. Also, this is a method newly introduced by the Oracle Corporation in their Java SE 8 release.

Example of Iterator in Java

Below is the example of Iterator in Java:

Code:

import java.io.*;
import java.util.*;
public class IteratorExample {
public static void main(String[] args)
{
ArrayList<String> val = new ArrayList<String>();
val.add("Iteration started");
val.add("Printing iteration1");
val.add("Printing iteration2");
val.add("Printing iteration3");
val.add("End of iteration");
// Iterates through the list
Iterator iter = val.iterator();
System.out.println("The values of iteration are as follows: ");
while (iter.hasNext())
System.out.println(iter.next() + " ");
System.out.println();
}
}

Output:

Iterator in Java

Iterator methods throw exceptions

In a list of elements, an iterator can fetch information only on the existing elements. Therefore, it will crash or throw an exception if tried to access an element that is not present in the next iteration. Here we shall get to know the different kinds of exceptions we get while implementing the iterator methods.

1. next() method

While iterating through a set of elements and fetching them by this method.

  • NoSuchElementException: This occurs if the next() tries to retrieve an element that does not exist in the present list. Hence always a hasNext() has to be used before calling next().

2. remove() method

There are 2 kinds of exceptions that can occur here:

  • IllegalStateException: If the remove() method is called before the next() method, then this exception is thrown. This is because the method attempts to remove an element that is not yet specified by the next() method and hence fails. To resolve this exception, next() must be called to refer to the first item and then remove() can be called to remove the same from the list.
  • UnsupportedOperationException: This exception is usually thrown when modifying a list object by adding or removing an operation that does not support modification. For example, when an array is tried to convert to a list by Arrays.asList throws this exception. This is because the List object will have a fixed size as the wrapper creates it from ArrayList, and hence modification will not be allowed. To resolve this issue, convert the Arrays.asList to ArrayList or LinkedList object before performing any operations like add/remove on the same.

Syntax:

//ArrayList is created from the list having fixed size
list = new ArrayList<String>(list);
Iterator<String> iter = list.iterator();
while(iter.hasNext()){
if( iter.next().equals("First iteration") ){
iter.remove();
}
}

Methods of ListIterator

These methods allow the iterator to traverse in both directions of the collection object. Following are some of them:

  • add(): This method inserts the object value given and is returned when the next() method is called.
  • hasNext(): This method is the same as the one mentioned in iterator types, which returns Boolean true/false depending on the next element having a value or not.
  • hasPrevious(): This method is opposite to hasNext() and returns Boolean true if the list has a previous element and vice versa.
  • next(): This method retrieves the next element from the given list.
  • previous(): This method retrieves the previous element from the list.
  • remove(): This deletes the present element from the list. When this method is called either before the next() or previous() function, it throws “IllegalStateException”.

Example for ListIterator

Below is an example in ArrayList for ListIterator.

Code:

import java.util.*;
public class IteratorExample {
public static void main(String args[]) {
// Creating an array list
ArrayList array = new ArrayList();
// add elements to the array list
array.add("First element");
array.add("Second element");
array.add("Third element");
array.add("Fourth element");
array.add("Fifth element");
array.add("Sixth element");
// Displaying elements of an array
System.out.println("Printing input of the array: ");
Iterator iter = array.iterator();
while(iter.hasNext()) {
Object value = iter.next();
System.out.println(value + " ");
}
System.out.println();
// To update the elements of iteration
ListIterator listiter = array.listIterator();
while(listiter.hasNext()) {
Object value = listiter.next();
listiter.set(value + "+");
}
System.out.print("Updated array elements are as follows: ");
iter = array.iterator();
while(iter.hasNext()) {
Object value = iter.next();
System.out.print(value + " ");
}
System.out.println("\n");
// To display the contents in backward direction
System.out.println("Printing elements in backward direction: ");
while(listiter.hasPrevious()) {
Object value = listiter.previous();
System.out.print(value + " ");
}
System.out.println();
}
}

Output:

Iterator in Java

Advantages of Iterators in Java

Below are the advantages of Iterators:

  1. It supports all classes under the Collection interface.
  2. The methods of an iterator are quite simple and easy to understand and implement.
  3. Elements of a Collection can be easily modified (add/remove) using Iterators.
  4. Accessing elements through Iterators will not lead to run-time exceptions.
  5. Data handling is efficient.
  6. It can iterate over various variables concurrently by holding each variable’s state of iteration separately.

Limitations of Iterators in Java

Below are the limitations of Iterators:

  1. Java iterator can iterate only in one direction, i.e. forward direction.
  2. It cannot be used to iterate between two different data structures concurrently.
  3. It cannot be used to backtrace an element.
  4. It does not allow modification of the structure of the element being iterated as it stores its position.
  5. It might be inefficient in certain cases were traversing through the elements directly is more efficient.

Conclusion

Iterators are the most commonly used method to retrieve elements from the collection interface. It is called Universal Java Cursor as it is applicable across all the Collection classes.

Recommended Article

This is a guide to Iterator in Java. Here we discuss methods and examples of Iterator in Java along with its Limitations and Advantages. You can also go through our other suggested articles to learn more –

  1. Overriding in Java
  2. Iterators in C#
  3. Java Collection Interview Questions
  4. Java Iterate Map

The above is the detailed content of Iterator in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Java CommandsNext article:Java Commands