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 Program to Iterate through linkedHashset
// Using the for-each loop
import java.io.*;
import java.util.LinkedHashSet;
class GFG {
public static void main(String[] args)
{
LinkedHashSet<String> gfg
= new LinkedHashSet<String>();
// Adding element to LinkedHashSet
gfg.add("Geeks");
gfg.add("for");
gfg.add("geeks");
// iterating LinkedHashSet using enhanced for loop
for (String itr : gfg) {
System.out.println(itr);
}
}
}
Output
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.
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 code to demonstrate
// the iterating over LinkedHashSet
// Using iterators
import java.io.*;
import java.util.*;
class IteratingLinkedHashSet {
public static void main(String[] args)
{
// Instantiate an object of Set
// Since LinkedHashSet implements Set
// Set points to LinkedHashSet
Set<String> gfg = new LinkedHashSet<String>();
// Elements are added using add() method
gfg.add("Geek");
gfg.add("For");
gfg.add("Geeks");
gfg.add("Courses");
gfg.add("Interview Prep");
gfg.add("Doubt Classes");
// Iterating through the LinkedHashSet
Iterator itr = gfg.iterator();
while (itr.hasNext()){
System.out.println( itr.next() );
}
}
}
Output
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.
Syntax:
set.stream().forEach()
Return: Returns a sequential stream considering collection as its source.
// Java code to demonstrate
// the iterating over LinkedHashSet
// Using JDK 1.8 streams
import java.io.*;
import java.util.*;
class GFG {
public static void main(String[] args)
{
LinkedHashSet<Integer> gfg = new LinkedHashSet<Integer>();
// Elements are added using add() method
gfg.add(9);
gfg.add(7);
gfg.add(11);
gfg.add(43);
gfg.add(2);
// Using forEach Method using Stream.
gfg.stream().forEach(System.out::println);
}
}
Output
9 7 11 43 2
Time complexity: O(N), where N is no. of elements of LinkedHashSet.