Home » LinkedHashSet in Java

Java LinkedHashSet Class

Java HashSet class hierarchy

Java LinkedHashSet class is a Hashtable and Linked list implementation of the Set interface. It inherits the HashSet class and implements the Set interface.

The important points about the Java LinkedHashSet class are:

  • Java LinkedHashSet class contains unique elements only like HashSet.
  • Java LinkedHashSet class provides all optional set operations and permits null elements.
  • Java LinkedHashSet class is non-synchronized.
  • Java LinkedHashSet class maintains insertion order.

Note: Keeping the insertion order in the LinkedHashset has some additional costs, both in terms of extra memory and extra CPU cycles. Therefore, if it is not required to maintain the insertion order, go for the lighter-weight HashMap or the HashSet instead.

Hierarchy of LinkedHashSet class

The LinkedHashSet class extends the HashSet class, which implements the Set interface. The Set interface inherits Collection and Iterable interfaces in hierarchical order.

LinkedHashSet Class Declaration

Let’s see the declaration for java.util.LinkedHashSet class.

Constructors of Java LinkedHashSet Class

Constructor Description
HashSet() It is used to construct a default HashSet.
HashSet(Collection c) It is used to initialize the hash set by using the elements of the collection c.
LinkedHashSet(int capacity) It is used to initialize the capacity of the linked hash set to the given integer value capacity.
LinkedHashSet(int capacity, float fillRatio) It is used to initialize both the capacity and the fill ratio (also called load capacity) of the hash set from its argument.

Java LinkedHashSet Example

Let’s see a simple example of the Java LinkedHashSet class. Here you can notice that the elements iterate in insertion order.

FileName: LinkedHashSet1.java

Output:

One  Two  Three  Four  Five  

Note: We can also use the enhanced for loop for displaying the elements.

Java LinkedHashSet example ignoring duplicate Elements

sFileName: LinkedHashSet2.java

Output:

       Ravi         Vijay         Ajay  

Remove Elements Using LinkeHashSet Class

FileName: LinkedHashSet3.java

Output:

The hash set is: [Java, T, Point, Good, Website]  true  After removing the element, the hash set is: [Java, T, Point, Website]  false  

Java LinkedHashSet Example: Book

FileName: Book.java

Output:

101 Let us C Yashwant Kanetkar BPB 8  102 Data Communications & Networking Forouzan Mc Graw Hill 4  103 Operating System Galvin Wiley 6  

Next TopicJava TreeSet class

You may also like