Difference Between Iterator and Spliterator in Java
Last Updated :
15 Oct, 2020
The Java Iterator interface represents an object capable of iterating through a collection of Java objects, one object at a time. The Iterator interface is one of the oldest mechanisms in Java for iterating collections of objects (although not the oldest — Enumerator predated Iterator).
Moreover, an iterator differs from the enumerations in two ways:
1. Iterator permits the caller to remove the given elements from the specified collection during the iteration of the elements.
2. Method names have been enhanced.
Java
// Java program to illustrate Iterator interface
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
public class JavaIteratorExample1 {
public static void main(String[] args)
{
// create a linkedlist
List<String> list = new LinkedList<>();
// Add elements
list.add("Welcome");
list.add("to");
list.add("our");
list.add("website");
// print the list to the console
System.out.println("The list is given as : "
+ list);
// call iterator on the list
Iterator<String> itr = list.iterator();
// itr.hasNext() returns true if there
// is still an element next to the current
// element pointed by iterator
while (itr.hasNext()) {
// Returns the next element.
System.out.println(itr.next());
}
// Removes the last element.
itr.remove();
// print the list after removing an
// element
System.out.println(
"After the remove() method is called : "
+ list);
}
}
OutputThe list is given as : [Welcome, to, our, website]
Welcome
to
our
website
After the remove() method is called : [Welcome, to, our]
Like Iterator and ListIterator, Spliterator is a Java Iterator, which is used to iterate elements one-by-one from a List implemented object.
The main functionalities of Spliterator are:
- Splitting the source data
- Processing the source data
The Interface Spliterator is included in JDK 8 for taking the advantages of parallelism in addition to sequential traversal. It is designed as a parallel analogue of an iterator.
Java
// Java program to illustrate a Spliterator
import java.util.*;
import java.util.stream.Stream;
public class InterfaceSpliteratorExample {
public static void main(String args[])
{
// Create an object of array list
ArrayList<Integer> list = new ArrayList<>();
// Add elements to the array list
list.add(101);
list.add(201);
list.add(301);
list.add(401);
list.add(501);
// create a stream on the list
Stream<Integer> str = list.stream();
// Get Spliterator object on stream
Spliterator<Integer> splitr = str.spliterator();
// Get size of the list
// encountered by the
// forEachRemaining method
System.out.println("Estimate size: "
+ splitr.estimateSize());
// Print getExactSizeIfKnown
// returns exact size if finite
// or return -1
System.out.println("Exact size: "
+ splitr.getExactSizeIfKnown());
// Check if the Spliterator has all
// the characteristics
System.out.println("Boolean Result: "
+ splitr.hasCharacteristics(
splitr.characteristics()));
System.out.println("Elements of ArrayList :");
// print elements using forEachRemaining
splitr.forEachRemaining(
(n) -> System.out.println(n));
// Obtaining another Stream to the array list.
Stream<Integer> str1 = list.stream();
splitr = str1.spliterator();
// Obtain spliterator using trySplit() method
Spliterator<Integer> splitr2 = splitr.trySplit();
// If splitr can be partitioned use splitr2 first.
if (splitr2 != null) {
System.out.println("Output from splitr2: ");
splitr2.forEachRemaining(
(n) -> System.out.println(n));
}
// Now, use the splitr
System.out.println("Output from splitr1: ");
splitr.forEachRemaining(
(n) -> System.out.println(n));
}
}
OutputEstimate size: 5
Exact size: 5
Boolean Result: true
Elements of ArrayList :
101
201
301
401
501
Output from splitr2:
101
201
Output from splitr1:
301
401
501
Difference between Iterator and Spliterator in java :
Iterator
| Spliterator
|
---|
Introduced in Java 1.2 | Introduced in Java 1.8 |
Iterator only iterates elements individually | Spliterator traverse elements individually as well as in bulk |
It is an iterator for whole collection API | It is an iterator for both Collection and Stream API, except Map implementation classes |
It uses external iteration | It uses internal iteration. |
It is a Universal iterator | It is Not a Universal iterator |
It does not support parallel programming | It supports parallel programming by splitting the given element set so that each set can be processed individually. |
Similar Reads
Difference Between StringTokenizer and Split Method in Java Legacy classes and interfaces are the classes and interfaces that formed the Collection Framework in the earlier versions of Java and how now been restructured or re-engineered. Splitting of String is basically breaking the string around matches of the given regular expression. Strings can be split
3 min read
Difference between Iterator and Enumeration in Java with Examples When working with Java Collections, it's essential to understand the differences between Iterator and Enumeration. Both are used for traversing elements within a collection, but they serve different purposes and have varying capabilities.IteratorAn Iterator is a versatile tool in Java that allows yo
5 min read
Difference Between Streams and Collections in Java Collection is an in-memory data structure, which holds all the values that the data structure currently has. Every element in the Collection has to be computed before we add it to the Collection. Operations such as searching, sorting, insertion, manipulation, and deletion can be performed on a Colle
3 min read
Convert an Iterator to Stream in Java Given an Iterator, the task is to convert it into Stream in Java. Examples: Input: Iterator = {1, 2, 3, 4, 5} Output: {1, 2, 3, 4, 5} Input: Iterator = {'G', 'e', 'e', 'k', 's'} Output: {'G', 'e', 'e', 'k', 's'} Approach: Get the Iterator. Convert the iterator to Spliterator using Spliterators.split
1 min read
Convert an Iterator to a List in Java Given an Iterator, the task is to convert it into List in Java. Examples: Input: Iterator = {1, 2, 3, 4, 5} Output: {1, 2, 3, 4, 5} Input: Iterator = {'G', 'e', 'e', 'k', 's'} Output: {'G', 'e', 'e', 'k', 's'} Below are the various ways to do so: Naive Approach: Get the Iterator. Create an empty lis
2 min read
Enumeration vs Iterator vs ListIterator in Java Enumeration is an interface. It is used in the collection framework in java to retrieve the elements one by one. Enumeration is a legacy interface that is applicable only for legacy classes like Vector, HashTable, Stack, etc. It provides a single direction iteration. By using enumeration, we can per
4 min read