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

  1. LinkedHashSet extends HashSet and implements the Set interface.

  2. It uses a combination of a hash table and a linked list to maintain the insertion order of elements.

  3. LinkedHashSet does not allow duplicate elements.

  4. It provides constant-time performance for the basic operations of add, remove, contains, and size.

  5. It does not allow null elements.

  6. 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.