Use app×
QUIZARD
QUIZARD
JEE MAIN 2026 Crash Course
NEET 2026 Crash Course
CLASS 12 FOUNDATION COURSE
CLASS 10 FOUNDATION COURSE
CLASS 9 FOUNDATION COURSE
CLASS 8 FOUNDATION COURSE
0 votes
136 views
in JAVA by (178k points)
An Iterator in Java is a powerful tool for traversing collections. It is used to loop through a collection of objects and retrieve each object one by one. With keywords such as Java Iterator, iteration, collection, loop, and objects being among the most searched terms in Java, mastering the use of an Iterator is essential for efficient programming. Learn how to use an Iterator in Java and explore its features with our expert guide.

Please log in or register to answer this question.

2 Answers

0 votes
by (178k points)

Java Iterator

Java Iterator is an interface provided by the Java Collections framework that allows you to iterate over a collection of objects. The Iterator interface provides methods to traverse, access, and remove elements from a collection. It is a way of accessing the elements of a collection without exposing the underlying data structure.

Getting an Iterator:

To get an iterator for a collection, you can use the iterator() method of the Collection interface. This method returns an instance of the Iterator interface that you can use to iterate over the elements of the collection.

Here is an example of how to get an iterator for an ArrayList:

import java.util.ArrayList;
import java.util.Iterator;

public class IteratorExample {

    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<String>();
        list.add("One");
        list.add("Two");
        list.add("Three");

        // Get an iterator for the list
        Iterator<String> iterator = list.iterator();

        // Loop through the collection using the iterator
        while(iterator.hasNext()) {
            String element = iterator.next();
            System.out.println(element);
        }
    }
}
 

In this example, we first create an ArrayList and add three elements to it. We then get an iterator for the list using the iterator() method and use it to loop through the elements of the list.

Looping Through a Collection:

Once you have obtained an iterator for a collection, you can use it to loop through the elements of the collection. The Iterator interface provides two methods to do this: hasNext() and next().

The hasNext() method returns true if there are more elements in the collection and false otherwise. The next() method returns the next element in the collection.

Here is an example of how to loop through a collection using an iterator:

import java.util.ArrayList;
import java.util.Iterator;

public class IteratorExample {

    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<String>();
        list.add("One");
        list.add("Two");
        list.add("Three");

        // Get an iterator for the list
        Iterator<String> iterator = list.iterator();

        // Loop through the collection using the iterator
        while(iterator.hasNext()) {
            String element = iterator.next();
            System.out.println(element);
        }
    }
}
 

In this example, we use the hasNext() method to check if there are more elements in the list and the next() method to get the next element in the list.

Removing Items from a Collection:

The Iterator interface also provides a method to remove elements from a collection while iterating through it. The remove() method removes the last element returned by the iterator from the underlying collection.

Here is an example of how to remove elements from a collection using an iterator:

import java.util.ArrayList;
import java.util.Iterator;

public class IteratorExample {

    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<String>();
        list.add("One");
        list.add("Two");
        list.add("Three");

        // Get an iterator for the list
        Iterator<String> iterator = list.iterator();

        // Loop through the collection using the iterator
        while(iterator.hasNext()) {
            String element = iterator.next();
            if(element.equals("Two")) {
                iterator.remove();
            }
        }

        // Print the modified list
        System.out.println(list);
    }
}
 

In this example, we use the remove() method of the Iterator interface to remove the element "Two" from the list. Note that we can only remove elements from a collection using an iterator. If we try to remove elements using a for-each loop, we will get a ConcurrentModificationException.

0 votes
by (178k points)

FAQs on Java Iterator

Q: What is a Java Iterator? 

A: A Java Iterator is an interface that provides a way to iterate over a collection of objects, such as an ArrayList or HashSet.

Q: How do I use a Java Iterator? 

A: To use a Java Iterator, you first need to create an instance of it for the collection you want to iterate over. You can then use methods such as next() to access the next element in the collection, and hasNext() to check if there are any more elements.

Example code:

List<String> list = new ArrayList<String>();
list.add("apple");
list.add("banana");
list.add("orange");

Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
    String fruit = iterator.next();
    System.out.println(fruit);
}
 

This code creates an ArrayList of strings, adds three elements to it, and then creates an Iterator for the list. It then uses a while loop to iterate over the list, printing out each element using the Iterator's next() method.

Q: Can I modify the collection while using an Iterator? 

A: Yes, you can modify the collection while using an Iterator, but you need to use the Iterator's remove() method to remove elements, rather than the collection's own remove() method.

Example code:

List<String> list = new ArrayList<String>();
list.add("apple");
list.add("banana");
list.add("orange");

Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
    String fruit = iterator.next();
    if (fruit.equals("banana")) {
        iterator.remove();
    }
}

System.out.println(list);
 

This code creates the same ArrayList as before, but removes the element "banana" using the Iterator's remove() method. It then prints out the remaining elements in the list using System.out.println().

Important Interview Questions and Answers on J Java Iterator

Q: What is a Java Iterator and how does it work?

Java Iterator is an interface used to traverse and manipulate elements in a collection. It provides methods to check if the collection has more elements, retrieve the next element, and remove the current element. The Iterator is used in combination with the Collection interface, which provides the methods to add, remove, and retrieve elements.

Q: What are the methods provided by the Java Iterator interface?

The Java Iterator interface provides the following methods:

  • boolean hasNext(): returns true if there are more elements in the collection.
  • E next(): returns the next element in the collection.
  • void remove(): removes the current element from the collection.

Q: How do you use an Iterator in Java?

To use an Iterator in Java, you first need to create an instance of it by calling the iterator() method on the collection object. Then, you can use the hasNext() method to check if there are more elements in the collection, and the next() method to retrieve the next element. If you want to remove an element from the collection while iterating over it, you can use the remove() method.

Example code:

List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");

Iterator<String> it = names.iterator();
while (it.hasNext()) {
    String name = it.next();
    System.out.println(name);
    if (name.equals("Bob")) {
        it.remove();
    }
}
 

In this example, we create a list of names and add three names to it. Then, we create an Iterator object by calling the iterator() method on the list. We use a while loop to iterate over the elements in the list, and print each name to the console. If the name is "Bob", we remove it from the list using the remove() method of the Iterator.

Related questions

0 votes
1 answer
asked Apr 25, 2023 in JAVA by kvdevika (178k points)
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Apr 25, 2023 in JAVA by kvdevika (178k points)

Welcome to Sarthaks eConnect: A unique platform where students can interact with teachers/experts/students to get solutions to their queries. Students (upto class 10+2) preparing for All Government Exams, CBSE Board Exam, ICSE Board Exam, State Board Exam, JEE (Mains+Advance) and NEET can ask questions from any subject and get quick answers by subject teachers/ experts/mentors/students.

Categories

...