Java ArrayList - spliterator() Method
The java.util.ArrayList.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.ArrayList.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 an ArrayList ArrayList<Integer> MyList = new ArrayList<Integer>(); //populating the ArrayList MyList.add(10); MyList.add(20); MyList.add(30); MyList.add(40); MyList.add(50); //creating spliterator object on the ArrayList Spliterator<Integer> splitr = MyList.spliterator(); //display content of the ArrayList //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 an ArrayList ArrayList<Integer> MyList = new ArrayList<Integer>(); //populating the ArrayList MyList.add(10); MyList.add(20); MyList.add(-30); MyList.add(-40); MyList.add(-50); //creating spliterator object on the ArrayList Spliterator<Integer> splitr = MyList.spliterator(); //printing estimateSize of the ArrayList System.out.println("Estimated size: " + splitr.estimateSize()); //display content of the ArrayList //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 - ArrayList