×

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

Types of Events in Java

One of Java's key ideas is the principle of an event. Events in Java are activities that result in a change in the state or behavior of an object. The...

4 minutes read.

Dangling Else problem in Java

A language interpretation uncertainty is the hanging other issue. The following two types of condition executed code are both possible in programming: 1. if-then-else form 2. if-then form When dealing with the nested...

3 minutes read.

Application of Array in Java

In this article we are going to acknowledge about what the array is, types of arrays and their applications. What is an array? An array is often a set of interrelated elements...

4 minutes read.

Java Garbage Collection Interview Questions

One of the key areas of Java is garbage collection. Garbage collection enables apps to manage memory automatically. Interviewers frequently ask inquiries about garbage collection. Q1: What is the purpose of...

6 minutes read.

Ternary Operator in Java

In some cases, the if...else expression in Java can be replaced by a ternary operator. Visit the Java if...else statement first before learning about the ternary operator. Ternary operator in Java A...

3 minutes read.

Java Base64 Encoding and Decoding

Introduction to Encoding and Decoding Encoding is the process of putting the sequence of characters like letters, numbers, punctuations, and other symbols into a specialised format for the efficient transmission or...

11 minutes read.

Perfect Number Program in Java

Perfect Number Program in Java A perfect number is a number whose sum of all the factors, excluding the number itself, is equal to the number. For example, 28 is a...

4 minutes read.

File Operation in Java

In Java, a file is an Abstract data type. These are used to store the data which is related. Files are named storage locations. With a file we can perform...

7 minutes read.

Logger class in Java

Logging is a crucial component of Java that aids developers in tracking down mistakes. The logging technique is included with the computer language Java. The possibility of collect the log...

7 minutes read.

Star Pattern Programs in Java

Star Pattern Programs in Java The star pattern programs in Java is the part of pattern programs in Java, which we discussed earlier. Right Triangle Star Pattern Filename: StarPatternExample.java public class StarPatternExample {              public static void...

4 minutes read.

Java Integer toUnsignedLong() method

The toUnsignedLong() method of Java Integer class returns a long value by simply converting the given argument to long after an unsigned conversion. Syntax public static long toUnsignedLong (int  x) Parameters The parameter ‘x’...

1 minute read.

Skyline Problem in Java

The skyline of a city is the outer edge of the pattern created by all of its structures when viewed from a distance. Return the skyline that these buildings together...

4 minutes read.

The Maximum Rectangular Area in a Histogram in Java

Continuous bars should be used to form the largest possible rectangle. We'll assume in the interest of convenience that each bar's width is 1. Naive Approach In this method, each bar will be...

6 minutes read.

Design of JDBC

Java applications may interface using database systems from many vendors using the Java Database Connectivity (JDBC) Application Software Interface (API) from Sun Microsystem. To connect spreadsheets, JDBC and database drivers...

3 minutes read.

Class definition in Java

The class definition in Java Java is an object-oriented programming language. We essentially know that programming languages based on object-oriented paradigms have classes and objects in their concepts as main, which...

6 minutes read.

Java List Node

In Java, List Node is the same as the single linked list, which is the collection of nodes. So, we can say, the list nodes are grouped together to get...

8 minutes read.

Deadlock in Java

Deadlock is when two or more processes wait for the state to do their tasks, but none of them can do so. It is a very common problem that one...

6 minutes read.

Sorting Algorithms in Java

Sorting Algorithms in Java Sorting is the technique that puts the elements of an array or list either in descending or ascending order. For example, take an array A, whose elements...

3 minutes read.

How to Create Different Packages for Different Classes in Java

Packages in Java In Java, Packages are an assortment of classes, sub-packages, and connection points. i.e. A package addresses a word reference that contains a connected gathering of styles and points...

7 minutes read.

Java Write File

In this post, we'll examine various Java programming methods for writing into files. Since this class is character-oriented due to how it is used in file handling in Java, it...

4 minutes read.