×

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

How to write basic Java Programs

Java Basic Programs In this section, we will learn how to write basic Java programs. But first we need to take care of the following requirement list. To execute a Java program,...

4 minutes read.

Number Pattern Programs in Java

Number Pattern Programs in Java: Number pattern programs are part of pattern programs. In the previous section, we have learned the approach to print the pattern program in Java. To...

6 minutes read.

Stack Program in Java

Stack Program in Java The Stack class is part of the collection framework that inherits the Vector class. Thus, the Stack class can also be called a subclass of the Vector...

5 minutes read.

Pangram Program in Java

If a string comprises all alphabet letters from A to Z or from a to z without regard to case, it is referred to as a pangram. Some examples of pangram...

3 minutes read.

Java Math log1p() Method

The log1p() method of Math class returns the natural logarithmic sum for the specified double argument and 1. Its value is much closer to result of ln(1 + x). Syntax: public static...

2 minutes read.

How to compare dates in Java

Introduction: In Java, dates can be compared using a similar interface's compareTo() technique. This method returns 'zero' if each date is the same, returns a rate "more than 0" if...

6 minutes read.

Applet Life Cycle in Java

In this article, we are going to acknowledge you about what a applet is, what is its life cycle and stages in life cycle, along with the syntax and example...

4 minutes read.

How to remove last character from String in Java

In java, there are predominantly three classes connected with the string. The classes are String, StringBuilder, and StringBuffer class that gives techniques connected with string control. Eliminating the first and...

5 minutes read.

Java file Reader

File Reader: It is used to read the data from files. This class inherits the properties from Input Stream Reader Class. File Reader is for reading characters from the file. Input Stream: Java.io...

4 minutes read.

Resultset in java

Resultset: A result set is an interface that is present in the package java.sql and the resultset is used to store the data that are returned from the database table after...

5 minutes read.

Three-way operator in Java

The ternary operator in Java is the only conditional operator that takes three operands. It's a popular one-line substitute for the if-then-else expression among Java programmers. If-else clauses can be...

3 minutes read.

Object Oriented Programming (OOPs)

Since the dawn of earth, we have kept on evolving. The need for evaluation comes with the aim of improving the existing systems when something inappropriate is found for the...

5 minutes read.

Iterate JSON array in Java

This article is going to equip the knowledge about what JSON array is and how it works and also how is it distinct with the generic array. Json Array Ordered lists of...

4 minutes read.

Java Xmx

This section will explain what Xmx in Java is and how to establish a Java application's maximum heap size. When we execute a Java application, it occasionally displays an error message...

3 minutes read.

Hybrid Inheritance in Java

The most crucial OOPs concept in Java is inheritance, which enables the transfer of a class's properties to another class. It describes the Is-A relationship generally. We can create a...

3 minutes read.

Java New Keyword

To create a class instance in Java, use the new keyword. In other words, it returns a reference to the memory that was allocated for a new object and instantiates...

3 minutes read.

Java Char Keyword

The java char keyword is a data type which is defined as character data type.Char keyword belongs to a primitive data type where the data types are classified into primitive...

4 minutes read.

How to check Date is Greater in Java?

In this article, you will be acknowledged about how to check if the given date is greater than the other date or not. We are simply comparing the dates and...

7 minutes read.

Java Enum

Enumerations are used in programming languages to represent collections of named constants. For instance, the four suits in a deck of playing cards might represent four iterators named Club, Diamond,...

3 minutes read.

Java Program to remove duplicate characters in a string

In strings, we can find many characters present one or more times in a string; accessing a particular character is difficult due to repetition. Duplicate characters will present in the...

5 minutes read.