ConcurrentLinkedQueue spliterator() method in Java
The spliterator()
method in ConcurrentLinkedQueue
class returns a Spliterator over the elements in this queue. Spliterator is a Java 8 interface that is used to traverse and partition elements of a source. It is used to traverse the elements of a collection one by one and perform some operations on each element.
Syntax:
Spliterator<E> spliterator()
Where,
- E
is the type of elements returned by the Spliterator.
Example:
ConcurrentLinkedQueue<String> queue = new ConcurrentLinkedQueue<>();
queue.add("Java");
queue.add("Python");
queue.add("C++");
queue.add("JavaScript");
Spliterator<String> spliterator = queue.spliterator();
spliterator.forEachRemaining(System.out::println);
Output:
Java
Python
C++
JavaScript
Another example using tryAdvance() method:
ConcurrentLinkedQueue<Integer> queue = new ConcurrentLinkedQueue<>();
queue.add(10);
queue.add(20);
queue.add(30);
queue.add(40);
Spliterator<Integer> spliterator = queue.spliterator();
spliterator.tryAdvance(System.out::println);
spliterator.tryAdvance(System.out::println);
Output:
10
20