Difference between hashset and treeset in java

Let’s learn difference between hashset and treeset in java.

Difference between hashset and treeset in java

HashSetTreeSet
stores object in random order.sorted according to natural order. If not use compareTo() method.
uses equals() method for comparison.uses compareTo() method for ordering.
backed by hashmap.backed by Navigable TreeMap.
hashset is better and faster.a bit slower.
gives constant time performance.TreeSet guarantees log(n) time cost

treeset vs hashset example:

// hashset example
import java.util.HashSet;
public class HashSetExample
{
   public static void main(String[] args)
   {
      HashSet<String> hs = new HashSet<String>();
      hs.add("hello");
      hs.add("world");
      hs.add("core");
      hs.add("java");
      // duplicate elements are removed
      hs.add("hello");
      // printing HashSet elements
      System.out.println("HashSet elements: ");
      for(String str : hs)
      {
         System.out.println(str);
      }
   }
}


Output:

HashSet elements:
core
world
java
hello


// treeset example
import java.util.TreeSet;
public class TreeSetDemo
{
   public static void main(String[] args)
   {
      TreeSet<String> ts = new TreeSet<String>();
      ts.add("hello");
      ts.add("world");
      ts.add("core");
      ts.add("java");
      // duplicate elements are removed
      ts.add("hello");
      // printing TreeSet elements
      System.out.println("TreeSet elements: ");
      for(String str : ts)
      {
         System.out.println(str);
      }
   }
}


Output:

TreeSet elements:
core
hello
java
world


Also read – major features of java