Java LinkedList spliterator() Method
Example
Use a Spliterator
to loop through items in a list:
import java.util.LinkedList;
import java.util.Spliterator;
public class Main {
public static void main(String[] args) {
// Make a collection
LinkedList<String> cars = new LinkedList<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 returns a Spliterator
for the list.
A spliterator is a special type of iterator. To learn how to use iterators, see our Java Iterator tutorial.
The Spliterator
is considerably different from an ordinary iterator. The purpose of a spliterator is to separate a collection into smaller pieces so that each piece can be processed by a separate thread. The Spliterator
interface has two important methods:
trySplit()
- Returns a new spliterator which can iterate through (usually and approximately) half of the elements that the original spliterator has access to, while the original spliterator can iterate through the remaining half.tryAdvance(Consumer action)
- Moves to the next item that is available to the spliterator and tries to perform an action on it. If there is no next item then it returnsfalse
. The action can be defined by a lambda expression.
Syntax
public Spliterator spliterator()
Technical Details
Returns: | A Spliterator object. |
---|---|
Java version: | 1.8+ |
Related Pages
❮ LinkedList Methods