- Collection Framework in JavaCollections Class in JavaList Interface in Java with ExamplesArrayList in JavaVector Class in JavaLinkedList in JavaQueue Interface In JavaPriorityQueue in JavaSet in JavaHashSet in JavaLinkedHashSet in JavaMap in the JavaHashMap in JavaHashtable in JavaLinkedHashMap in Java
LinkedHashSet in Java
LinkedHashSet in Java is a subclass of HashSet that maintains a doubly-linked list of elements, in the order in which they were inserted into the set. This allows for iteration over the elements in the order in which they were added to the set.
The syntax for creating a LinkedHashSet is the same as that for creating a HashSet:
LinkedHashSet<Type> set = new LinkedHashSet<>();
Features of LinkedHashSet
LinkedHashSet extends HashSet and implements the Set interface.
It uses a combination of a hash table and a linked list to maintain the insertion order of elements.
LinkedHashSet does not allow duplicate elements.
It provides constant-time performance for the basic operations of add, remove, contains, and size.
It does not allow null elements.
It is not synchronized and is not thread-safe.
Here are some examples of how to use a LinkedHashSet
Example 1: Adding Elements
LinkedHashSet<String> set = new LinkedHashSet<>();
set.add("apple");
set.add("banana");
set.add("orange");
set.add("banana");
System.out.println(set);
Output:
[apple, banana, orange]
Notice that the duplicate "banana" was not added to the set, and the elements are printed in the order in which they were added.
Example 2: Removing Elements
set.remove("orange");
System.out.println(set);
Output:
[apple, banana]
Example 3: Checking if an element is present in a LinkedHashSet.
System.out.println(set.contains("apple"));
System.out.println(set.contains("mango"));
Output:
true
false
Example 4: Iterating over Elements
for (String element : set) {
System.out.println(element);
}
Output:
apple
banana
Notice that the elements are printed in the order in which they were added.
LinkedHashSet has the same time complexity as HashSet for add, remove, contains and size operations, which is O(1) on average. However, iterating over the elements of a LinkedHashSet is slower than iterating over the elements of a HashSet, because of the extra overhead of maintaining the doubly-linked list. If you need to maintain the order of insertion and also need constant-time performance for basic operations, LinkedHashSet is a good choice.