×

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

Stack in Java

Java provides a number of collection frameworks to store the collection of objects. Among the collection of data structures " Stack " is one of them. Stack is one of...

5 minutes read.

InputMismatchException in Java

What is InputMismatchException? One of the most frequent errors in Java is the InputMismatchException. Because the InputMismatchException is a subtype of the java.lang, it is an unchecked exception. RuntimeException.Because it is...

4 minutes read.

How to Convert Integer to String in Java

How to Convert int to String in Java It is used when you want to convert an integer to String. You can convert int to String by using the following methods: Using...

3 minutes read.

How to install Java in Windows 10

To make programs that can run on our systems, we need to install the programming language related software in our systems. Different programming language requires a different type of software aka...

6 minutes read.

Best Practices to use String Class in Java

Use String Builder or String Buffer for String concatenation in place of + operator.Compare two strings by equals( ) method instead == operator.Call .equals( ) method on a known String...

3 minutes read.

Order of Execution of Constructors in Java Inheritance

Constructor in Java There are several distinctions between a method and a function object() in Java. The name of the function object()  is identical to the class name. There is no...

4 minutes read.

Java Math scalb() Method

The scalb() method of Java Math class returns a single perfectly rounded product of floating-point and member of the double value set as if performed by d*2scaleFacor rounded value. Syntax: public static...

2 minutes read.

Economical number in Java

Economical number is said to be economically efficient if the number of digits after prime factorization of the original number with their powers is less than the number of digits...

3 minutes read.

Java logger

Logging is a crucial Java feature that aids developers in identifying issues. The logging methodology is included with Java as the programming language. It offers the Logging API, which debuted...

7 minutes read.

Relatively Prime in Java

In this article, you will be very well equipped with a knowledge of a relatively prime number and also Java programs to determine whether a given integer is a relatively...

4 minutes read.

Group by in Java 8

By using this groupingBy() method, developers can directly able to perform the "GROUP BY" operation. The thing is, now, the Java 8 programming language allows the programmers to do this...

3 minutes read.

Sleeping Barber Problem in Java

The barbershop in this issue has one barber, one barber chair, and N chairs for customers in the waiting area. We may demonstrate the issue by keeping with the original...

6 minutes read.

Fork Join in Java

Multithreaded processors are being introduced in new computer systems today. The operation is faster due to multicore CPUs. Therefore, it becomes essential for a programmer to leverage multithreaded processors effectively...

4 minutes read.

Tilt operator in Java | Tilde operator in Java Example

The symbol designates it as a unary operator (pronounced as the tilde). It gives back the bit's complement or inverse. Every 0 turns into a 1, and every 1 back...

3 minutes read.

Check the presence of Substring in a String in java

In java, the string can be treated as class and datatype. The string contains words and numbers but should be in double-quotes. Example: ” Omsairam” Substring The part of the string is called...

2 minutes read.

Java Extends vs Implements

Java: We known that the java is a pure object oriented programming language. Java programming language consists of many features such as portable, plat form independence, secured, robust, simple, architecture neutral,...

4 minutes read.

List of Constants in Java

In this tutorial, we are going to deal with constants available in Java.Every programming language has its constants. Similarly, Javaalso has got constants of its own. In this tutorial, we will...

6 minutes read.

Java Map Interface

A map is a collection that maps keys to values, with no duplicate keys allowed. The elements in a map are key/value pairs. HashMap: HashMap stores the keys in a...

3 minutes read.

Java Session

Session indicates interval of time. A session is a simple  time interval in which servers and client interacts. To maintain the state of the client or user we use technologies...

5 minutes read.

Computing Digit Sum of all Numbers from 1 to n in Java

In this tutorial, we will discuss various methods to compute the sum of digits of all numbers beginning from 1 to n through a Java program. We will achieve it through...

7 minutes read.