Java PriorityQueue - spliterator() Method
The java.util.PriorityQueue.spliterator() method is used to create a late-binding and fail-fast spliterator over the elements in the given priority queue.
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 priority queue.
Exception
NA.
Example:
In the example below, the java.util.PriorityQueue.spliterator() method is used to create a spliterator over the elements in the given queue.
import java.util.*; public class MyClass { public static void main(String[] args) { //creating a priority queue PriorityQueue<Integer> PQueue = new PriorityQueue<Integer>(); //populating the priority queue PQueue.add(10); PQueue.add(20); PQueue.add(30); PQueue.add(40); PQueue.add(50); //creating spliterator object on the priority queue Spliterator<Integer> splitr = PQueue.spliterator(); //display content of the priority queue //using tryAdvance method System.out.print("PQueue contains: "); while(splitr.tryAdvance((n) -> System.out.print(n + " "))); } }
The output of the above code will be:
PQueue contains: 10 20 30 40 50
Example:
Lets consider another example to learn the concept of spliterator over the elements in the given queue.
import java.util.*; public class MyClass { public static void main(String[] args) { //creating a priority queue PriorityQueue<Integer> PQueue = new PriorityQueue<Integer>(); //populating the priority queue PQueue.add(10); PQueue.add(20); PQueue.add(30); PQueue.add(40); PQueue.add(50); //creating spliterator object on the priority queue Spliterator<Integer> splitr = PQueue.spliterator(); //printing estimateSize of the priority queue System.out.println("Estimated size: " + splitr.estimateSize()); //display content of the priority queue using //forEachRemaining method System.out.print("PQueue contains: "); splitr.forEachRemaining((n) -> System.out.print(n + " ")); } }
The output of the above code will be:
Estimated size: 5 PQueue contains: 10 20 30 40 50
❮ Java.util - PriorityQueue