1. Introduction
In Java, the LinkedHashSet class is part of the Java Collections Framework and is a member of the Set framework. It is an ordered version of HashSet that maintains a doubly-linked List across all elements. When iterating through a LinkedHashSet, the elements are returned in the order in which they were inserted into the set. In this blog post, we will explore different ways to iterate through a LinkedHashSet.
2. Program Steps
1. Create a LinkedHashSet and add elements to it.
2. Iterate through the LinkedHashSet using an Iterator.
3. Iterate through the LinkedHashSet using a for-each loop.
4. Iterate through the LinkedHashSet using a lambda expression.
3. Code Program
import java.util.Iterator;
import java.util.LinkedHashSet;
public class LinkedHashSetIteration {
public static void main(String[] args) {
// Step 1: Create a LinkedHashSet and add elements to it
LinkedHashSet<String> linkedHashSet = new LinkedHashSet<>();
linkedHashSet.add("Apple");
linkedHashSet.add("Banana");
linkedHashSet.add("Cherry");
// Step 2: Iterate through the LinkedHashSet using an Iterator
System.out.println("Iterating using Iterator:");
Iterator<String> iterator = linkedHashSet.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
// Step 3: Iterate through the LinkedHashSet using a for-each loop
System.out.println("Iterating using for-each loop:");
for (String fruit : linkedHashSet) {
System.out.println(fruit);
}
// Step 4: Iterate through the LinkedHashSet using a lambda expression
System.out.println("Iterating using lambda expression:");
linkedHashSet.forEach(fruit -> System.out.println(fruit));
}
}
Output:
Iterating using Iterator: Apple Banana Cherry Iterating using for-each loop: Apple Banana Cherry Iterating using lambda expression: Apple Banana Cherry
4. Step By Step Explanation
Step 1: A LinkedHashSet named linkedHashSet is created, and three elements ("Apple", "Banana", and "Cherry") are added to it.
Step 2: We obtain an Iterator for the linkedHashSet and use a while loop to iterate through the set, printing each element.
Step 3: A for-each loop is used to iterate through the linkedHashSet, printing each element.
Step 4: A lambda expression, in conjunction with the forEach method, is used to iterate through the linkedHashSet, printing each element.
In each step, the elements are printed in the order they were added to the LinkedHashSet, demonstrating the order-preserving property of LinkedHashSet.