Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is HashSet?
2.1.
HashSetExample.java
2.2.
Java
2.2.1.
Output 
3.
What is TreeSet?
3.1.
TreeSetExample.java
3.2.
Java
3.2.1.
Output
4.
Difference between Hashset and Treeset in Java
5.
Code
5.1.
Null Values in HashSet
5.2.
Java
5.2.1.
Output
5.3.
Null Values in TreeSet
5.4.
Java
5.4.1.
Output
5.5.
Comparison in HashSet
5.6.
Java
5.6.1.
Output
5.7.
Comparison in TreeSet
5.8.
Java
5.8.1.
Output
6.
Similarities Between HashSet and TreeSet
7.
Which one is better to use?
8.
Frequently Asked Questions
8.1.
Which is better HashSet or TreeSet?
8.2.
What is the difference between HashSet and TreeSet?
8.3.
Which is faster for searching operations TreeSet or HashSet?
8.4.
What is the difference between TreeSet and TreeMap?
9.
Conclusion
Last Updated: Mar 27, 2024
Medium

Difference Between HashSet and TreeSet

Introduction

A HashSet in Java implements the Set interface and is supported by a HashMap, whereas a TreeSet implements sorted sets and is backed by a TreeMap.

hashset vs treeset

We will first look at both the sets definitions and how it gets implemented. Later in the blog, we will look at HashSet and TreeSet differences. We will also cover the programs for a thorough understanding of the topic.

What is HashSet?

A HashSet is a data structure used in computer science to store a collection of unique elements. It is a part of the collections framework in many programming languages, including Java and C#.

In a HashSet, elements are stored in a way that ensures uniqueness; that is, no two elements in the set can be equal according to the equals() method (or equivalent) of the elements. Additionally, elements in a HashSet are not stored in any particular order.

This data structure is optimized for fast insertion, deletion, and lookup operations. Internally, it typically uses a hash table or a similar mechanism to achieve efficient performance.

HashSetExample.java

  • Java

Java

import java.util.HashSet;   
public class HashSetEx
{  
public static void main(String[] args)  
{  
/*creating a HashSet */
HashSet<Integer> hashSet= new HashSet<Integer>();  
/* add elements to HashSet  */
hashSet.add(5);
hashSet.add(2);
hashSet.add(3);
hashSet.add(6);
hashSet.add(13);
System.out.println("Elements in HashSet are ");
/* iterate in hashSet */
for(int hash: hashSet){
System.out.println(hash);
}
}
}
You can also try this code with Online Java Compiler
Run Code


Output 

Elements in HashSet are
2
3
5
6
13
Output image


You can also read about the Longest Consecutive Sequence.

What is TreeSet?

A TreeSet is another data structure used to store a collection of elements in computer science, particularly in languages like Java. It is part of the collections framework and is designed to store unique elements in sorted order.

Internally, a TreeSet is typically implemented using a self-balancing binary search tree, such as a red-black tree. This structure maintains the elements in sorted order, which allows for efficient retrieval of elements in sorted sequence. The elements are sorted based on their natural ordering (if they implement the Comparable interface) or by a specified comparator provided during construction.

TreeSetExample.java

  • Java

Java

import java.util.TreeSet;   
public class TreeSetEx
{  
public static void main(String[] args)  
{  
/* creating a TreeSet  */
TreeSet<String> treeSet= new TreeSet<String>();  
/* add elements to HashSet */ 
treeSet.add("yellow");
treeSet.add("blue");
treeSet.add("green");
/* Duplicate elements will not be stored */
treeSet.add("blue");
System.out.println("Elements in TreeSet are “);
System.out.println(treeSet);
}
}
You can also try this code with Online Java Compiler
Run Code


Output

Elements in TreeSet are
[blue, green,yellow]

Difference between Hashset and Treeset in Java

Now lets us see HashSet vs TreeSet. Here we will look at the differences between them.

Properties

HashSet

TreeSet

Implementation It internally uses HashMap to store the elements. Internally it uses TreeMap to store the elements.
Data Structure  The Data structure that HashSet uses is HashTable. The Data Structure that TreeSet uses is a Red-Black Tree.
Time Complexity To add or remove the element from HashSet, the time complexity is O(1). For adding or removing the element from TreeSet, the time complexity is O(log(n)).
Null Values Only one null element can be stored in the HashSet. No null elements are allowed.
Comparison The hashCode() or equals() method is used to compare the elements it uses. The compare() and compareTo() method is used for comparison.
Sorted values There is no guarantee that the elements will be stored in sorted order. TreeSet maintains the Sorted order.
Performance It is faster than TreeSet. TreeSet is slower than HashSet.
Values to Store HashSet can store Heterogenous values. You can store only homogenous values in TreeSet.
Methods In comparison to TreeSet, HashSet offers fewer methods. TreeSet has more methods in comparison to HashSet.
Iteration order To iterate HashSet elements, it uses the arbitrary method. It has sorted values.

 

Also read aboutt - Difference between HashMap and HashSet

Code

Let’s try to understand some of the differences through programs.

Code implementation

Null Values in HashSet

When you try to insert Null values in HashSet

  • Java

Java

import java.util.HashSet;   
public class HashSetEx
{  
public static void main(String[] args)  
{  
/* creating a HashSet  */
HashSet<Integer> hashSet= new HashSet<Integer>();  
/* add elements to HashSet   */
hashSet.add(5);
hashSet.add(2);
hashSet.add(3);
hashSet.add(6);
hashSet.add(0);
System.out.println("Elements in HashSet are ");
/* iterate in hashSet */
for(int hash: hashSet){
System.out.println(hash);
}
}
}
You can also try this code with Online Java Compiler
Run Code


Output

Elements in HashSet are
0
2
3
5
6

 

Null Values in TreeSet

When you try to insert null values into TreeSet

  • Java

Java

import java.util.TreeSet;   
public class TreeSetEx
{  
public static void main(String[] args)  
{  
/* creating a TreeSet  */
TreeSet<String> treeSet= new TreeSet<String>();  
/* add elements to HashSet  */
treeSet.add("Mango");
treeSet.add("banana");
treeSet.add(null);
/* Duplicate elements will not be stored */
treeSet.add("blue");
System.out.println("Elements in TreeSet are ");
System.out.println(treeSet);
}
}
You can also try this code with Online Java Compiler
Run Code


Output

Output image

Comparison in HashSet

When you compare values in HashSet you will use the equals method.

  • Java

Java

import java.util.HashSet;
public class Main
{
   public static void main(String[] args) {
   HashSet<Integer> h1= new HashSet<Integer>();
   /* add elememts */
   h1.add(1);
   h1.add(2);
   h1.add(5);
   h1.add(6);
   System.out.println("Elements in HashSet h1 are ");
/* iterate in hashSet */
for(int hash: h1){
System.out.println(hash +" ");
}
HashSet<Integer> h2= new HashSet<Integer>();
   /* add elememts */
   h2.add(1);
   h2.add(2);
   h2.add(5);
   h2.add(6);
   System.out.println("Elements in HashSet h2 are ");
for(int hash: h2){
System.out.println(hash +" ");
}
boolean value= h1.equals(h2);
System.out.println(value);
}
}
You can also try this code with Online Java Compiler
Run Code


Output

Elements in HashSet h1 are 
1 
2 
5 
6 
Elements in HashSet h2 are 
1 
2 
5 
6 
true

Comparison in TreeSet

Using the comparator method in TreeSet 

  • Java

Java

import java.util.Comparator;
import java.util.TreeSet;

class MyComparison implements Comparator<String> {
 public int compare(String str1, String str2) {
   String a, b;

   a = str1;
   b = str2;

   return b.compareTo(a);
 }
 
}
public class Main
{
   public static void main(String[] args) {
   TreeSet<String> treeSet = new TreeSet<String>(new MyComparator());

   treeSet.add("blue");
   treeSet.add("orange");
   treeSet.add("green");
   treeSet.add("yellow");
   treeSet.add("purple");
   treeSet.add("Dark");

   for (String value : treeSet)
     System.out.print(value + " ");

   System.out.println();
   }
}
You can also try this code with Online Java Compiler
Run Code

 

Output

yellow purple orange green blue Dark

Similarities Between HashSet and TreeSet

  • The Set interface is implemented by both classes
     
  • They do not permit the use of duplicate values
     
  • Thread safety is not provided by HashSet or TreeSet
     
  • They are not synchronized, but we can synchronize them using the Collections.synchronizedSet() function
     
  • Both classes' iterators are fail-fast in nature. If we try to edit an iterator after it has been generated, it throws a ConcurrentModificationException
     
  • Both use the clone() function to produce a clone of their objects using the shallow copy technique

Which one is better to use?

HashSet offers O(1) performance for add, remove, and contains, but does not maintain order. TreeSet maintains elements in sorted order using a binary tree but has O(log n) worst-case performance for basic operations. Use HashSet if you need constant time performance and don't require order, and use TreeSet if you need sorted elements and efficient traversal in sorted order, especially for larger sets. The choice depends on specific use cases and set sizes.

Check out this problem - Duplicate Subtree In Binary Tree

Frequently Asked Questions

Which is better HashSet or TreeSet?

HashSet performs search, insert, and delete operations in constant time. This makes HashSet faster than TreeSet, which takes O(Log n) time. The reason behind this is that HashSet is implemented using a hash table, while TreeSet uses a sorted data structure.

What is the difference between HashSet and TreeSet?

HashSet is an unordered collection of unique elements, relying on hashing for fast operations. TreeSet is a sorted collection, using a self-balancing binary search tree.

Which is faster for searching operations TreeSet or HashSet?

HashSet offers faster search operations.

What is the difference between TreeSet and TreeMap?

TreeSet ensures elements are sorted, which aids in retrieval. TreeMap, like TreeSet, is sorted but stores key-value pairs.

Conclusion

In this blog, we have learned about the Difference Between HashSet and TreeSet. We started by introducing the sets and covered the differences between their sets. We have coded programs for a thorough understanding of HashSet vs TreeSet.

To learn more about Sets, please refer to our blog

Hashing 

Learn HashMaps 

String Hashing

Difference Between Rank and Dense Rank

Also check out the Interview guide for Product Based Companies as well as some of the Popular interview problems from top tech companies like Amazon, Adobe, Google, Uber, Microsoft, etc.

Refer to our guided pathways on Code studio to learn more about DSACompetitive ProgrammingJavaScriptSystem Design, etc. Enroll in our courses, and use the accessible sample exams and questions as a guide. For placement preparations, look at the interview experiences and interview package.

Live masterclass