1. Introduction
The LinkedHashSet class in Java is part of the Java Collections Framework and extends the HashSet class. It maintains the insertion order, which means while iterating through the set, the elements will be returned in the order in which they were inserted. In this blog post, we will perform some basic operations like add, remove, contains, and iterate using LinkedHashSet.
2. Program Steps
1. Create a LinkedHashSet.
2. Add elements to the LinkedHashSet.
3. Remove an element from the LinkedHashSet.
4. Check if the LinkedHashSet contains a specific element.
5. Iterate through the LinkedHashSet and print the elements.
3. Code Program
import java.util.LinkedHashSet;
public class LinkedHashSetBasicOperations {
public static void main(String[] args) {
// Step 1: Create a LinkedHashSet
LinkedHashSet<String> linkedHashSet = new LinkedHashSet<>();
// Step 2: Add elements to the LinkedHashSet
linkedHashSet.add("Element1");
linkedHashSet.add("Element2");
linkedHashSet.add("Element3");
System.out.println("LinkedHashSet after adding elements: " + linkedHashSet);
// Step 3: Remove an element from the LinkedHashSet
linkedHashSet.remove("Element2");
System.out.println("LinkedHashSet after removing Element2: " + linkedHashSet);
// Step 4: Check if the LinkedHashSet contains a specific element
boolean containsElement1 = linkedHashSet.contains("Element1");
System.out.println("Contains Element1: " + containsElement1);
// Step 5: Iterate through the LinkedHashSet and print the elements
System.out.print("Iterating through LinkedHashSet: ");
for (String element : linkedHashSet) {
System.out.print(element + " ");
}
}
}
Output:
LinkedHashSet after adding elements: [Element1, Element2, Element3] LinkedHashSet after removing Element2: [Element1, Element3] Contains Element1: true Iterating through LinkedHashSet: Element1 Element3
4. Step By Step Explanation
Step 1: We initialize a LinkedHashSet named linkedHashSet.
Step 2: Elements "Element1", "Element2", and "Element3" are added to the linkedHashSet, and the set is printed, displaying the elements in the order they were added.
Step 3: The element "Element2" is removed from the linkedHashSet, and the updated set is printed.
Step 4: We check whether the linkedHashSet contains "Element1" using the contains method, which returns true, indicating that "Element1" is present in the set.
Step 5: Finally, we iterate through the linkedHashSet using a for-each loop and print the elements, which are displayed in the order they were inserted.