Performance Comparison Between TreeSet and HashSet in Java

This tutorial explains all the differences and common features between  TreeSet and HashSet. Indeed, this is a very popular question in java collections, such as ArrayList vs Vector and HashTable vs HashMap. Probably the most important difference is the performance.

TreeSet vs HashSet

1)  HashSet provides consistent performance time for basic operations such as: add, remove, contains and size. HashSet is faster than TreeSet and it will be a very good choice if you don't need to sort the elements, because HashSet has no sorting system. TreeSet  Guaranteed log(n) time for basic operations (addremove  et  contains).

2)  HashSet  does not guarantee that items will be sorted. TreeSet ensures that elements are ordered in ascending order or defined by the interface Comparable or whatever you specify in the constructor defined by the interface Comparator of Java.

3) Traversal performance depends on the initial capacity and load factor of HashSet. TreeSet has no parameters that influence the performance of the course.

4) TreeSet offers methods that do not have in HashSet :  first(), last(), headSet() and tailSet().

5) HashSet uses the method  equals() to compare two objects and to detect duplicate objects. TreeSet uses the compareTo(). equals() returns true if both objects are equal and compareTo() should return zero.

The similarities between TreeSet and HashSet in Java

HashSet  and  TreeSet  have a lot of things that are common, let's take a look:

1) Both implement the interface java.util.Set, CE  which means that they do not allow the insertion of duplicate elements.

2) The two implementations are not synchronized. You can make them synchronized by using the Collections.synchronizedSet().

3) If you want a sorted set, it's faster to add elements to HashSet and then convert them to TreeSet  than to create a TreeSet and add elements.

In the end, we can say that the choice of use completely depends on your needs.

Example of HashSet:

import java.util.HashSet; 

public class example {

public static void main(String[] args) {

HashSet< String> hset = new HashSet< String> ();

hset.add("1");
hset.add("3");
hset.add("2");
hset.add("5");

for(String s: hset)
System.out.println(s);
}
}

Result:
3
2
1
5
TreeSet example:

import java.util.TreeSet; 

public class example {

public static void main(String[] args) {

TreeSet< String> tset = new TreeSet< String> ();

tset.add("1");
tset.add("3");
tset.add("2");
tset.add("5");

for(String s: tset)
System.out.println(s);
}
}

Result:
1
2
3
5
References:
Difference between HashSet and TreeSet in Java
Hashset vs Treeset