A LinkedHashSet in Java is a data structure that combines the features of both a HashSet and a LinkedList. It maintains a linked list of the entries in the set, which allows for predictable iteration order, while also providing constant-time complexity for the basic operations (add, remove, contains).
You can use a LinkedHashSet in situations where you need to maintain the order of insertion of elements, along with the uniqueness of elements. Some common use cases for LinkedHashSet include:
Preserving insertion order: If you need to iterate over the elements of a set in the order they were inserted, a LinkedHashSet can be used.
Removing duplicates while preserving order: If you have a collection of elements where duplicates need to be eliminated but the order of the remaining elements must be maintained, a LinkedHashSet can be used.
Here's an example of how you can use a LinkedHashSet in Java:
import java.util.LinkedHashSet;
public class LinkedHashSetExample {
public static void main(String[] args) {
LinkedHashSet<String> set = new LinkedHashSet<>();
// Adding elements to the LinkedHashSet
set.add("Apple");
set.add("Banana");
set.add("Orange");
set.add("Apple"); // Duplicate entry, will be ignored
// Iterating over the elements in the LinkedHashSet
for (String element : set) {
System.out.println(element);
}
// Checking if an element exists in the LinkedHashSet
boolean containsBanana = set.contains("Banana");
System.out.println("Contains Banana? " + containsBanana);
// Removing an element from the LinkedHashSet
boolean removed = set.remove("Orange");
System.out.println("Removed Orange? " + removed);
// Size of the LinkedHashSet
System.out.println("Size of LinkedHashSet: " + set.size());
}
}
No comments:
Post a Comment