×

Java Iterator

When iterating through, traversing, or retrieving the individual elements of a Collection or Flow object, a Java Cursor is leveraged as an iterator. In Java, there exist three types of cursors. They are namely

  • Iterator
  • Enumeration
  • ListIterator

In this article we are only discussing about the Iterator. The syntax, examples and methods are also discussed in this article.

Iterator

The Collection framework in Java uses iterators to get objects each one individually. Given that we may use it on any Collection object, it is a generic iterator. We can execute retrieve and eliminate functions using Iterator. With the added ability to remove an object, it is an enhanced form of Enumeration.

All Collection framework-implemented protocols, such as Set, List, Queue, Deque, and all supported classes of Data structure, need the use of an iterator anytime we want to iterate elements. For the complete collection framework, only the iterator cursor is exposed.

Syntax

Iterator itr = c.iterator();

Iterator Methods

Each Collection class provides the iterator() function. When using an iterator to cycle over a collection's data, first get an iterator to the collection's beginning by invoking the iterator() function on the collection. Establish a sequence that calls hasNext after that ( ). Keep repeating the loop until hasNext() yields true. Lastly, inside that loop, call next to get each element ( ).

The iterator interface consists of 3 methods:

  1. hasNext()
  2. next()
  3. remove()
  4. forEachRemaining()

hasNext()

There are no parameters accepted by the procedure. If there are still more components in the iteration, it satisfies the condition. It will result false if there are no further values.It is not necessary to invoke the next() method if there are no further components in the iteration. In simple terms, we can explain that the method is employed in order decide whether or not to invoke the next() method.

next()

It is comparable to the method hasNext(). Additionally, it doesn't take any parameters. It gives back E, the following element with in propagation. The NoSuchElementException is thrown if the iterative process or object collection runs out of factors to iterate.

remove()

There are no parameters needed for this technique either. This method doesn't have a return type. This method's primary purpose is to eliminate the final member that the iterator returned after going through the original collection. Only a small number of times per subsequent () method call how could the remove () method be requested. The iterator throws the UnSupportedOperationException if it is unable to support the remove method. If the following method has not yet been invoked, it also causes the IllegalStateException.

forEachRemaining()

It is the one Java Iterator method that accepts an input. Action is accepted as a variable. Action is simply what needs to be done. This method has no return type. until each of the left collection elements have been used or the function raises an exception, this method applies the specific individual operation to each of the left collection elements. Action throws exceptions, which are communicated to the caller. It throws a NullPointerException if the method is null.

Example

Let’s go through the simple program to understand the iterator. The program goes in the following manner.

Demo1.java

import java.io.*;  
import java.util.*;  
    
public class Demo1 {  
    public static void main(String[] args)  
    {  
        ArrayList<String> carModels = new ArrayList<String>();  
    
        carModels.add("Audi");  
        carModels.add("Mustang");  
        carModels.add("Ford");  
        carModels.add("Ferrari");  
        carModels.add("Land Rover");  
    
        Iterator it = carModels.iterator();  
    
        System.out.println("Car Models : ");  
    
        while (it.hasNext())  
            System.out.println(it.next() + " ");  
    
        System.out.println();  
    }  
}  

Output

Car Models :
Audi
Mustang
Ford
Ferrari
Land Rover

Advantages

  • These iterators can be used with any of the Collection package's classes, according to the users.
  • The read as well as remove functions are both fully functional in Java Iterator.
  • When using a for loop, an user can't modify (add or remove items from) the Collection; but, if they use a Java Iterator, they can easily do so.
  • For the Collection API, the Java Iterator is regarded as the Global Pointer.
  • The Java Iterator has very straightforward method names that are also very convenient when using.

Disadvantages

  • The Java Iterator just keeps track of iterations that move ahead. A Java Iterator is just a single - mode Iterator, to put it simply.
  • The Java Iterator does not support the replacement or expansion of a new component.
  • The Java Iterator sometimes doesn't store the multiple functions like CREATE and UPDATE in CRUD Operations.
  • Java Iterator only provides Consecutive iteration since, in contrast to the Spliterator, it does not provide traversal components in the continuous path.
  • Java Iterator does not enable more dependable performance to examine the large amount of information in contrast to Spliterator.

Related Topics

Java Polymorphism

The process of representing one form in multiple forms is known as Polymorphism. Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many and "morphs" means forms. So polymorphism means...

5 minutes read.

What’s New in Java 15

Sealed classes are the new concept that was introduced by Java 15. Sealed classes are a preview feature. Most of the features which are released in java 15 are in...

3 minutes read.

Reserved Keywords in Java

In Java, a reserved term is used as a code key called a keyword. Because they are predefined, these terms cannot be used for anything else. They cannot serve as...

3 minutes read.

ArrayList vs Vector in Java

ArrayList Vs. Vector in Java In Java, the two classes ArrayList and Vector both are associated with Java Collections Framework. Both classes implement java.util.List interface. Even so, these classes have noticeable...

4 minutes read.

Java Byte intValue() method

The intValue()  method of Java Integer class returns an int value for this Integer.  Syntax public int intValue()  Parameters NA  Specified by This method is specified by intValue in class Number  Return Value This method returns the numeric...

1 minute read.

Finding Odd Occurrence of a Number in Java

In this tutorial, we will learn how to find the odd occurrence of a number through a java program. Let us consider an array of non-negative integers. Here, except for one...

6 minutes read.

Java Buffer Reader

When a variable cannot change its value during run time is called a Static way of programming. In this programming, a variable is directly assigned to a value. Program: Import java.io.*; class  A {  ...

4 minutes read.

Java 8 filters list

A stream with the components of this stream that match the given predicate is provided by the streaming filter (Predicate predicate). This process is step-by-step. Because these operations are always...

4 minutes read.

Java Math pow() Method

The pow() method of Math class returns the value of first argument raised to the power of second argument i.e. ab. Syntax: public static double pow(double a, double b) Parameters: The parameters ‘a’ and...

3 minutes read.

Java Math abs() Method

The abs() method of Math class returns the absolute value of the argument where the argument can be int, double, float, long. Syntax public static int abs(int a) public static float abs(float a) public...

2 minutes read.

Java gc()

Garbage collection Java language provides different ways to perform the task of memory management. In Java, objects are declared and assigned references. Once lifeof an object is completed it is dereferenced...

4 minutes read.

Matrix Multiplication Program in Java

Matrix Multiplication Program in Java The matrix multiplication program in Java is the continuation of the matrix program in Java that we have already discussed earlier. In this section, we will...

3 minutes read.

Unicode System in Java

In this tutorial, we will understand the meaning and emergence of the Unicode system in java. The Unicode system is one of the important and useful features in the world...

6 minutes read.

How to Convert String to long in Java

How to Convert String to long in java It is used when you want to perform the mathematical operation on the String which contains long number then the conversion from String...

4 minutes read.

Java Buffered Writer

BufferWriter Class: It is used to write the data more efficiently. This class is present in the java.io package, it inherits the data from the Writer class. Writer class is...

4 minutes read.

Java HashSet

HashSet implements the set interface. It uses the hash table to make the collection to store different data types. The hash set is the unordered collection of different data types....

6 minutes read.

How to Convert String to float in Java

How to Convert String to Float in java It is used if you want to perform mathematical operations on the string that contains float number. You can convert String to float...

3 minutes read.

Method chaining in Java

Method chaining in Java is the act of calling a series of methods one after the other. The sole distinction between it and function Object () constructor chaining is the difference...

3 minutes read.

Constructor in Java with Example

Java Constructor  The constructor is used for object initialization. It's a block of code that initializes a newly created object. It contains a collection of statements that are executed at the...

5 minutes read.

Java Math log10() Method

The log10() method of Math class returns the base 10 logarithmic value for the specified double argument. Syntax: public static double log10(double a) Parameters: The parameter ‘a’ represents a double value. Return Value: The log10() method...

2 minutes read.