Showing posts with label LinkedHashSet. Show all posts
Showing posts with label LinkedHashSet. Show all posts

LinkedHashSet

In our previous tutorial we have discussed about LinkedHashMap and how its works. In this tutorial we will see about LinkedHashSet and what is the difference between HashMap and how its works. Lets list out the properites of LinkedHashSet

  • LinkedHashSet contains only unique values.
  • LinkedHashSet implements Set interface and extends HashSet class. So it acquires all properites of HashSet class.
  • The only difference between HashSet and LinkedHashSet is insertion order. HashSet won't maintain insertion order, were as LinkedHashSet always maintains the insertion order. 

Now lets see simple example which show how to use LinkedHashSet and difference between HashSet.


import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;

public class LinkedHashSetTest {
 
 public static void main(String[] args) {
  
  Set<String> hs = new HashSet<String>();
  Set<String> lhs = new LinkedHashSet<String>();
  
  hs.add("one");
  hs.add("two");
  hs.add("three");
  hs.add("three");
  hs.add("four");
  
  lhs.add("one");
  lhs.add("two");
  lhs.add("three");
  lhs.add("three");
  lhs.add("four");
  
  // Printing HashSet values.
  System.out.println("HashSet values :::::::::::::::");
  Iterator<String> itr = hs.iterator();
  while(itr.hasNext()){
   System.out.println(itr.next());
  }
  
  // Printing LinkedHashSet values.
  System.out.println("LinkedHashSet values :::::::::::::::");
  Iterator<String> itr1 = lhs.iterator();
  while(itr1.hasNext()){
   System.out.println(itr1.next());
  }
 }
}

OUTPUT:


HashSet values :::::::::::::::
two
one
three
four

LinkedHashSet values :::::::::::::::
one
two
three
four


In above program we have added 5 values in HashSet and LinkedHashSet with 1 duplicate value "three". Since Set won't allow duplicate value we can see only once "three" has printed. Next if we see the difference between HashSet and LinkedHashSet, insertion order has not followed in HashSet. But LinkedHashSet maintains the insertion order.