Java

Java – LinkedHashSet Class With Example

We have previously given lessons for TreeSet and HashSet. With the exception of the following differences, LinkedHashSet is similarly an implementation of the Set interface and is comparable to HashSet and TreeSet:

  • No kind of element order is preserved by HashSet.
  • The components are arranged by TreeSet in ascending order.
  • The insertion order is maintained by LinkedHashSet. The order in which the elements are sorted follows the order in which they were added to the set.

Example of LinkedHashSet:

import java.util.LinkedHashSet;
public class LinkedHashSetExample {
     public static void main(String args[]) {
         // LinkedHashSet of String Type
         LinkedHashSet<String> lhset = new LinkedHashSet<String>();

         // Adding elements to the LinkedHashSet
         lhset.add("Z");
         lhset.add("PQ");
         lhset.add("N");
         lhset.add("O");
         lhset.add("KK");
         lhset.add("FGH");
         System.out.println(lhset);

         // LinkedHashSet of Integer Type
         LinkedHashSet<Integer> lhset2 = new LinkedHashSet<Integer>();

         // Adding elements
         lhset2.add(99);
         lhset2.add(7);
         lhset2.add(0);
         lhset2.add(67);
         lhset2.add(89);
         lhset2.add(66);
         System.out.println(lhset2);
    }
}

Output:

[Z, PQ, N, O, KK, FGH]
[99, 7, 0, 67, 89, 66]

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button