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. When iterating through a HashSet the order is unpredictable, while a LinkedHashSet lets us iterate through the elements in the order in which they were inserted. When cycling through LinkedHashSet using an iterator, the elements will be returned to the order in which they were inserted.
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.util.*;
import java.lang.*;
import java.io.*;
class GFG {
public static void main(String[] args)
throws java.lang.Exception
{
LinkedHashSet<Integer> hashSet
= new LinkedHashSet<Integer>();
hashSet.add( 1 );
hashSet.add( 2 );
hashSet.add( 3 );
hashSet.add( 4 );
hashSet.add( 5 );
for (Integer element : hashSet)
System.out.println( "Element is " + element);
}
}
|
Output
Element is 1
Element is 2
Element is 3
Element is 4
Element is 5
Method 2: Using iterators
Java
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG {
public static void main(String[] args)
throws java.lang.Exception
{
LinkedHashSet<Integer> hashSet
= new LinkedHashSet<Integer>();
Custom inputs hashSet.add( 1 );
hashSet.add( 2 );
hashSet.add( 3 );
hashSet.add( 4 );
hashSet.add( 5 );
Iterator iter = hashSet.iterator();
while (iter.hasNext())
System.out.println( "Element is " + iter.next());
}
}
|
Output
Element is 1
Element is 2
Element is 3
Element is 4
Element is 5
Method 3: Using JDK 1.8 streams
Java
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG {
public static void main(String[] args)
throws java.lang.Exception
{
LinkedHashSet<Integer> hashSet
= new LinkedHashSet<Integer>();
hashSet.add( 1 );
hashSet.add( 2 );
hashSet.add( 3 );
hashSet.add( 4 );
hashSet.add( 5 );
Iterator iter = hashSet.iterator();
hashSet.stream().forEach(element -> {
System.out.println( "Element is " + element);
});
}
}
|
Output
Element is 1
Element is 2
Element is 3
Element is 4
Element is 5
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!