The spliterator() method of HashSet returns a Spliterator with the same elements as HashSet. The returned Spliterator is late-binding and fail-fast Spliterator. A late-binding Spliterator binds to the source of elements means HashSet at the point of first traversal, first split, or first query for estimated size, rather than at the time the Spliterator is created. It can be used with Streams in Java 8. Also it can traverse elements individually and in bulk too. Spliterator is better way to traverse over element because it provides more control on elements.
public Spliterator<E> spliterator()
Returns: This method returns a Spliterator over the elements in HashSet.
Below programs illustrate spliterator() method of HashSet:
Example 1: To demonstrate spliterator() method on HashSet which contains a set of Numbers.
list of Numbers: 32 23 45 63
Example 2: To demonstrate spliterator() method on HashSet which contains set of Students Names.
list of Students: Student Name: Rabi Student Name: Mohan Student Name: Sohan Student Name: Ram
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.