A Guide To Iterator In Java

May 12, 2023
A Guide to Iterator in Java



Introduced in Java 1.2, an iterator enables us to loop, extract, or remove elements and arguments from a collection. The object gets its name as it iterates or loops through a list to return desired items. Accessed via java.util package, Java iterator works by the iterator() method and can be applied multiple times within a collection.

new java job roles

Having explored the basics of iterators in Java, let’s explore three commonly used use cases or methods with examples.

Basic Java Iterator Example

// Import the ArrayList class and the Iterator class

import java.util.ArrayList;

import java.util.Iterator;

public class Main {

  public static void main(String[] args) {

    // Make a collection

    ArrayList<String> cars = new ArrayList<String>();

    cars.add("Ford");

    cars.add("Toyota");

    cars.add("Honda");

    cars.add("Mazda");

    // Get the iterator

    Iterator<String> it = cars.iterator();

    // Print the first item

    System.out.println(it.next());

  }

}

Output:

Ford

Three Methods to Use Java Iterator

A developer could use iterators in Java to perform the following operations:

  • Boolean hasNext()
  • Object next()
  • Void remove()

1) Boolean hasNext()

A commonly used operation in Java, it checks a collection for more elements, returns true if found, and false if all elements have been covered.

In the Java iterator example below, the hasNext() method is used with the while loop to iterate through the ‘integers’ Array List. Also, the next() method is applied to print each integer on a new line.

import java.util.ArrayList;

import java.util.Iterator;

public class Main {

    public static void main(String[] args) {

        // Making a collection

        ArrayList<String> integers = new ArrayList<String>();

        integers.add("1");

        integers.add("2");

        integers.add("3");

        integers.add("4");

        integers.add("5");

        // Calling an iterator

        Iterator<String> s = integers.iterator();

        while(s.hasNext()){

            System.out.println(s.next());

        }

    }

}

Output:

1

2

3

4

5

2) Object next()

The next() iterator in Java returns the immediate or next element in the list or collection. You get NoSuchElementException if the list is completed.

Below is a Java iterator example to use the above Java iterator to print the item in a list or collection.

import java.util.Iterator;

public class Main {

    public static void main(String[] args) {

        // Making a collection

        ArrayList<String> integers = new ArrayList<String>();

        integers.add("1");

        integers.add("2"); 

        integers.add("3");

        integers.add("4");

        integers.add("5");

        // Calling an iterator

        Iterator<String> s = integers.iterator();

        // Printing the five elements in a collection

            System.out.println(s.next());

            System.out.println(s.next());

            System.out.println(s.next());

            System.out.println(s.next());

            System.out.println(s.next());

          // This will throw in an exception as request exceeds element count

            System.out.println(s.next());

        }

    }

Output:

1

2

3

4

5

Exception in thread "main" java.util.NoSuchElementException
  at java.base/java.util.ArrayList$Itr.next(ArrayList.java:1000)
  at Main.main(Main.java:21)

3) void remove()

This Java iterator only works after the next() iterator and its function is to remove or exclude the current object from the collection. Attempting to use the void remove() without the next() iterator will get you IllegalStateException.

Below is a Java iterator example where three elements are removed from the collection as they fail to satisfy the condition.

import java.util.ArrayList;

import java.util.Iterator;

public class Main {

    public static void main(String[] args) {

        // Making a collection

        ArrayList<Integer> Num = new ArrayList<Integer>();

        Num.add(12);

        Num.add(24); 

        Num.add(11);

        Num.add(17);

        Num.add(5);

        // Printing the collection

        System.out.println(Num);

        // Calling an iterator

        Iterator<Integer> itr = Num.iterator();

        // Removing elements using the remove() method

        while(itr.hasNext()){

            Integer i = itr.next();

            if(i<15){

                itr.remove();

            }

        }

        System.out.println(Num);

    }

}

Output:

[12,   24,  11,  17,  5]

[24,  17]

Below is a Java iterator example of using the void remove() without the next() iterator to better understand what not to do.

import java.util.ArrayList;

import java.util.Iterator;

public class Main {

    public static void main(String[] args) {

        // Making a collection

        ArrayList<Integer> Num = new ArrayList<Integer>();

        Num.add(12);

        Num.add(24); 

        Num.add(11);

        Num.add(17);

        Num.add(5);

        // Printing the collection

        System.out.println(Num);

        // Calling an iterator

        Iterator<Integer> itr = Num.iterator();

        // Using the remove() method without the next() iterator

                itr.remove();

          }

}

Output:

(12, 24, 11, 17, 5]

Exception in thread "main" java.lang.I1legalstateexception

at java.base/java.util.ArrayListsItr.remove(ArrayList. java: 1010)
       at Main.main(Main.java:17)

Limitations of Java Iterators

The uses of iterators in Java are manifold as they help developers effectively manage lists and collections and loop elements in desirable ways. However, there are always some limitations to every function, which merit you turning to other tools or objects.

Most prominently, Java iterators don’t support backward iteration or allow adding new elements to the list or collection. Further, the function also doesn’t support update operations.

A Short Recap

This article presented an in-depth guide to Java iterators to help you understand when to use them, what they can do, the plausible exceptions or errors you may face and their limitations.

All in all, iterators in Java give developers their efforts worth as they help simplify collections and lists in desirable ways, extract the required elements, and remove the others.

The Java iterator examples presented in the article can be used as a guide to run similar commands and functions while designing applications in Java.

Also Read: How to use the toString() in Java

new Java jobs



author

admin


Candidate signup

Create a free profile and find your next great opportunity.

JOIN NOW

Employer signup

Sign up and find a perfect match for your team.

HIRE NOW

How it works

Xperti vets skilled professionals with its unique talent-matching process.

LET’S EXPLORE

Join our community

Connect and engage with technology enthusiasts.

CONNECT WITH US