WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Java Collections · Intermediate · question 38 of 100

What is the difference between an Iterator and a Spliterator in Java Collections?

📕 Buy this interview preparation book: 100 Java Collections questions & answers — PDF + EPUB for $5

In Java Collections, both Iterator and Spliterator are used to iterate over the elements of a collection, but they have some differences in their implementation.

Iterator is the older and more basic interface for iterating over a collection. It allows sequential access to the elements in a collection and supports both remove() and hasNext() operations.

Spliterator is a newer and more advanced interface that was introduced in Java 8. It provides more powerful and efficient ways of traversing collections, especially when dealing with parallel streams. Spliterator supports splitting the collection into smaller parts that can be processed in parallel, and it also provides additional methods for iterating over collections, such as tryAdvance() and forEachRemaining().

Here’s an example code that demonstrates the differences between Iterator and Spliterator:

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

public class Example {
    public static void main(String[] args) {
        ArrayList<Integer> list = new ArrayList<>();
    
        // Add elements to the list
        for (int i = 0; i < 10; i++) {
            list.add(i);
        }
    
        // Iterate using an Iterator
        System.out.println("Iterator elements:");
        Iterator<Integer> iterator = list.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    
        // Iterate using a Spliterator
        System.out.println("Spliterator elements:");
        Spliterator<Integer> spliterator = list.spliterator();
        spliterator.forEachRemaining(System.out::println);
    }
}

In this example, we create an ArrayList and add 10 elements to it. We then iterate through the elements of the list using both an Iterator and a Spliterator.

Note that the Spliterator interface is intended to be used with Java 8 streams, which provide a more concise and expressive way of processing collections. However, Spliterator can also be used directly if more control over the iteration process is needed.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Java Collections interview — then scores it.
📞 Practice Java Collections — free 15 min
📕 Buy this interview preparation book: 100 Java Collections questions & answers — PDF + EPUB for $5

All 100 Java Collections questions · All topics