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.
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.