Java LinkedHashSet Class

  • LinkedHashSet Class extends extends HashSet class and Implements Set interface in collection interface hierarchy.
  • LinkedHashSet implementation differs from HashSet as it maintains doubly-linked list running through all of its entries.
  • It maintains element's entries in set as per it's insertion order. So it will allow you insertion order iteration over the set. So when you iterate over LinkedHashSet, In which order it will return elements? Answer is As per it's insertion order.
  • So you will get same copy of elements with the order how they inserted in set. 
  • LinkedHashSetis not synchronized.
LinkedHashSet Class hierarchy



Bellow given example will show you basic methods of  LinkedHashSet and it's usage.

package JAVAExamples;

import java.util.Iterator;
import java.util.LinkedHashSet;

public class LinkedHashSetExample {

 public static void main(String[] args) {
  LinkedHashSet<String> lhs = new LinkedHashSet<String>();
  // Add items to LinkedHashSet
  lhs.add("one");
  lhs.add("two");
  lhs.add("three");
  lhs.add("four");
  // Print LinkedHashSet.
  System.out.println(lhs);
  // Get size of LinkedHashSet.
  System.out.println("LinkedHashSet size Is : " + lhs.size());
  // Check if LinkedHashSet is empty?
  System.out.println("Is LinkedHashSet emplty? : " + lhs.isEmpty());
  // Iterate through LinkedHashSet.
  Iterator<String> itr = lhs.iterator();
  System.out.println("LinkedHashSet Items are : ");
  while (itr.hasNext()) {
   System.out.println(itr.next());
  }
  // Remove item from LinkedHashSet.
  lhs.remove("three");
  // Print LinkedHashSet.
  System.out.println("Now LinkedHashSet items are : " + lhs);
 }
}

Output :
[one, two, three, four]
LinkedHashSet size Is : 4
Is LinkedHashSet emplty? : false
LinkedHashSet Items are : 
one
two
three
four
Now LinkedHashSet items are : [one, two, four]

No comments:

Post a Comment