Iterate Through Elements of LinkedHashSet in Java
The LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked List across all elements. When the iteration order is needed to be maintained this class is used.
Input: ["Geeks", "for", "Geeks"] Output: Geeks for Geeks Input: [9, 4, 6, 2, 8] Output: 9 4 6 2 8
Different Ways to Iterate LinkedHashSet Elements:
- Using the for-each loop
- Using iterators
- Using JDK 1.8 streams
Method 1: Using the for-each loop
Geeks for geeks
Method 2: Using iterators
Iterate through the elements of LinkedHashSet using the iterator method. We will use the hasNext() method and the next() method along with the while loop to iterate through LinkedHashSet elements.
- E – the type of elements maintained by this set.
public Iterator<E> iterator()
Return: This method returns the element of LinkedHashSet in the same order as the input.
Geek For Geeks Courses Interview Prep Doubt Classes
Method 3: Using JDK 1.8 streams
Iterate through the elements of LinkedHashSet using the forEach method. We will iterate through the entire content using Stream. The stream represents a sequence of objects from a source, which supports aggregate operations.
Return: Returns a sequential stream considering collection as its source.
9 7 11 43 2
Time complexity: O(N), where N is no. of elements of LinkedHashSet.
Please Login to comment...