A LinkedHashSet in Java is an implementation of the Set interface that maintains insertion order of elements, which means when you iterate through a LinkedHashSet, the elements are returned in the order they were inserted. It combines the uniqueness property of HashSet with predictable iteration order provided by a linked list.
import java.util.LinkedHashSet;
public class LinkedHashSetExample {
public static void main(String[] args) {
// Creating a LinkedHashSet to store student names
LinkedHashSet<String> studentSet = new LinkedHashSet<>();
// Adding students to the LinkedHashSet
studentSet.add("Paani");
studentSet.add("Mahesh");
studentSet.add("Datta");
studentSet.add("Ganesh");
studentSet.add("Harsha");
// Attempting to add duplicate student (Mahesh)
boolean addedDuplicate = studentSet.add("Mahesh");
System.out.println("Duplicate 'Mahesh' added? " + addedDuplicate);
// Displaying the set of students
System.out.println("\nSet of students:");
for (String student : studentSet) {
System.out.println(student);
}
// Removing a student from the set
studentSet.remove("Datta");
// Displaying the updated set
System.out.println("\nUpdated set of students:");
for (String student : studentSet) {
System.out.println(student);
}
// Checking if the set contains a student
String searchStudent = "Harsha";
boolean containsStudent = studentSet.contains(searchStudent);
System.out.println("\nDoes the set contain '" + searchStudent + "'? " + containsStudent);
// Size of the set
System.out.println("Size of the set: " + studentSet.size());
// Clearing the set
studentSet.clear();
System.out.println("Is the set empty now? " + studentSet.isEmpty());
}
}
D:\>javac LinkedHashSetExample.java
D:\>java LinkedHashSetExample
Duplicate 'Mahesh' added? false
Set of students:
Paani
Mahesh
Datta
Ganesh
Harsha
Updated set of students:
Paani
Mahesh
Ganesh
Harsha
Does the set contain 'Harsha'? true
Size of the set: 4
Is the set empty now? true
Code language: JavaScript (javascript)
LinkedHashSet in Java combines the uniqueness property of HashSet with the predictable iteration order provided by a linked list. It offers efficient performance for basic operations and guarantees the order of elements based on insertion sequence. Understanding when to use LinkedHashSet based on its features can help in designing effective data structures and algorithms in Java applications.