what difference HashSet and TreeSet in java ?

In this section we will learn difference between HashSet and TreeSet in java .

HashSet VS TreeSet

1) HashSet gives better performance (faster) than TreeSet for the operations like add, remove, contains, size etc. HashSet offers constant time cost while TreeSet offers log(n) time cost for such operations.

2) HashSet does not maintain any order of elements while TreeSet elements are sorted in ascending order by default.

Similarities:

1) Both HashSet and TreeSet does not hold duplicate elements, which means both of these are duplicate free.

2) If you want a sorted Set then it is better to add elements to HashSet and then convert it into TreeSet rather than creating a TreeSet and adding elements to it.

3) Both of these classes are non-synchronized that means they are not thread-safe and should be synchronized explicitly when there is a need of thread-safe operations.

import java.util.HashSet;
import java.util.TreeSet;

public class Example1 {
public static void main(String[] args) {
 // HashSet declaration
      HashSet<String> hashset  = getHashSet();
}
public static HashSet<String> getHashSet(){
HashSet<String>  hashset  =  new HashSet<String>();

// Adding elements to the HashSet
      hashset.add("Item4");
      hashset.add("Item2");
      hashset.add("Item6");
      hashset.add("Item1");
      hashset.add("Item3");
      hashset.add("Item5");
      //add duplicate value
      hashset.add("Item3");
      System.out.println("HashSet values ALL :"+hashset);
   
      //TreeSet Declaration
      TreeSet<String> treeset  =  new TreeSet<String>();
      treeset.add("Item4");
      treeset.add("Item2");
      treeset.add("Item6");
      treeset.add("Item1");
      treeset.add("Item3");
      treeset.add("Item5");
      //add duplicate value
      treeset.add("Item3");
      System.out.println("TreeSet values ALL :"+treeset);
return hashset;
}
 
}

//result :

HashSet values ALL :[Item1, Item2, Item5, Item6, Item3, Item4]
TreeSet values ALL :[Item1, Item2, Item3, Item4, Item5, Item6]


we saw treeset display elements sorted in ascending order.


EmoticonEmoticon