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.
Example:
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
Java
import java.io.*;
import java.util.LinkedHashSet;
class GFG {
public static void main(String[] args)
{
LinkedHashSet<String> gfg
= new LinkedHashSet<String>();
gfg.add( "Geeks" );
gfg.add( "for" );
gfg.add( "geeks" );
for (String itr : gfg) {
System.out.println(itr);
}
}
}
|
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.
Type Parameters:
- E – the type of elements maintained by this set.
Syntax:
public Iterator<E> iterator()
Return: This method returns the element of LinkedHashSet in the same order as the input.
Java
import java.io.*;
import java.util.*;
class IteratingLinkedHashSet {
public static void main(String[] args)
{
Set<String> gfg = new LinkedHashSet<String>();
gfg.add( "Geek" );
gfg.add( "For" );
gfg.add( "Geeks" );
gfg.add( "Courses" );
gfg.add( "Interview Prep" );
gfg.add( "Doubt Classes" );
Iterator itr = gfg.iterator();
while (itr.hasNext()){
System.out.println( itr.next() );
}
}
}
|
OutputGeek
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.
Syntax:
set.stream().forEach()
Return: Returns a sequential stream considering collection as its source.
Java
import java.io.*;
import java.util.*;
class GFG {
public static void main(String[] args)
{
LinkedHashSet<Integer> gfg = new LinkedHashSet<Integer>();
gfg.add( 9 );
gfg.add( 7 );
gfg.add( 11 );
gfg.add( 43 );
gfg.add( 2 );
gfg.stream().forEach(System.out::println);
}
}
|
Time complexity: O(N), where N is no. of elements of LinkedHashSet.