Example
Utilize a Spliterator to iterate through the items in a list.
import java.util.ArrayList;
import java.util.Spliterator;
public class Main {
public static void main(String[] args ) {
// Make a collection ArrayList<String> cars = new ArrayList<String>();
cars .add("Volvo");
cars .add("BMW");
cars .add("Ford");
cars .add("Mazda");
// Get the spliterator and split it
Spliterator<String> it1 = cars .spliterator();
Spliterator<String> it2 = it1 .trySplit();
// Loop through the first spliterator
System.out .println("First spliterator");
while( it1 .tryAdvance( (n ) -> { System.out .println(n ); } ) );
// Loop through the second spliterator
System.out .println("\nSecond spliterator");
while( it2 .tryAdvance( (n ) -> { System.out .println(n ); } ) );
}
}
|
Note: The syntax while(it1.tryAdvance((n) -> { System.out.println(n); })); is equivalent to:
boolean x = it1 .tryAdvance( (n ) -> { System.out .println(n ); });
while(x ) {
x = it1 .tryAdvance( (n ) -> { System.out .println(n ); });
}
|
Definition and Usage
The spliterator() method retrieves a Spliterator for the list, which is a specialized type of iterator.
To understand how to work with iterators, refer to our Java Iterator tutorial.
The Spliterator differs significantly from a standard iterator. Its primary objective is to partition a collection into smaller segments, enabling independent processing by separate threads. The Spliterator interface encompasses two pivotal methods:
- trySplit(): Generates a new spliterator capable of traversing approximately half of the elements accessible to the original spliterator, leaving the remaining half for the original.
- tryAdvance(Consumer action): Progresses to the next available item for the spliterator and attempts to execute an action on it. If no next item exists, it returns false. The action can be specified via a lambda expression.
Syntax
public Spliterator spliterator()
|
Technical Details
Returns:
|
A Spliterator object.
|
Java version:
|
1.8+
|