Java LinkedList - spliterator() Method
The java.util.LinkedList.spliterator() method is used to create a late-binding and fail-fast spliterator over the elements in the list.
Syntax
public Spliterator<E> spliterator()
Here, E is the type of element maintained by the container.
Parameters
No parameter is required.
Return Value
Returns a spliterator over the elements in the list.
Exception
NA.
Example:
In the example below, the java.util.LinkedList.spliterator() method is used to create a spliterator over the elements in the given list.
import java.util.*; public class MyClass { public static void main(String[] args) { //creating a LinkedList LinkedList<Integer> MyList = new LinkedList<Integer>(); //populating the LinkedList MyList.add(10); MyList.add(20); MyList.add(30); MyList.add(40); MyList.add(50); //creating spliterator object on the LinkedList Spliterator<Integer> splitr = MyList.spliterator(); //display content of the LinkedList //using tryAdvance method System.out.print("MyList contains: "); while(splitr.tryAdvance((n) -> System.out.print(n + " "))); } }
The output of the above code will be:
MyList contains: 10 20 30 40 50
Example:
Lets consider another example to learn the concept of spliterator over the elements in the given list.
import java.util.*; public class MyClass { public static void main(String[] args) { //creating a LinkedList LinkedList<Integer> MyList = new LinkedList<Integer>(); //populating the LinkedList MyList.add(10); MyList.add(20); MyList.add(-30); MyList.add(-40); MyList.add(-50); //creating spliterator object on the LinkedList Spliterator<Integer> splitr = MyList.spliterator(); //printing estimateSize of the LinkedList System.out.println("Estimated size: " + splitr.estimateSize()); //display content of the LinkedList using //forEachRemaining method System.out.print("MyList contains: "); splitr.forEachRemaining((n) -> System.out.print(n + " ")); } }
The output of the above code will be:
Estimated size: 5 MyList contains: 10 20 -30 -40 -50
❮ Java.util - LinkedList