BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Difference between HashSet and TreeSet

Last Updated: September 11, 2022 by Chaitanya Singh | Filed Under: java

In this article we are gonna discuss the differences between HashSet and TreeSet.

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.

Examples:

HashSet example

import java.util.HashSet;
class HashSetDemo{ 
  public static void main(String[] args) {
     // Create a HashSet
     HashSet<String> hset = new HashSet<String>();
 
     //add elements to HashSet
     hset.add("Abhijeet");
     hset.add("Ram");
     hset.add("Kevin");
     hset.add("Singh");
     hset.add("Rick");
     // Duplicate removed
     hset.add("Ram"); 
 
     // Displaying HashSet elements
     System.out.println("HashSet contains: ");
     for(String temp : hset){
        System.out.println(temp);
     }
  }
}

Output:

HashSet contains: 
Rick
Singh
Ram
Kevin
Abhijeet

TreeSet example

import java.util.TreeSet;
class TreeSetDemo{ 
  public static void main(String[] args) {
     // Create a TreeSet
     TreeSet<String> tset = new TreeSet<String>();
 
     //add elements to TreeSet
     tset.add("Abhijeet");
     tset.add("Ram");
     tset.add("Kevin");
     tset.add("Singh");
     tset.add("Rick");
     // Duplicate removed
     tset.add("Ram"); 
  
     // Displaying TreeSet elements
     System.out.println("TreeSet contains: ");
     for(String temp : tset){
        System.out.println(temp);
     }
  }
}

Output: Elements are sorted in ascending order.

TreeSet contains: 
Abhijeet
Kevin
Ram
Rick
Singh

Top Related Articles:

  1. LinkedHashMap in Java
  2. HashSet in Java With Examples
  3. How to convert a HashSet to a TreeSet
  4. Converting a HashSet to an Array
  5. Swing – JButton tutorial and examples

Tags: Collections, Java-HashSet, Java-TreeSet

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Comments

  1. Anil Kumar Veluru says

    September 17, 2016 at 5:04 PM

    One more important difference is that HashSet allows null object but TreeSet doesn’t allow null Object and throw NullPointerException, Why, because TreeSet uses compareTo() method to compare keys and compareTo() will throw java.lang.NullPointerException.

    Reply
  2. Anshul says

    October 8, 2016 at 6:14 PM

    Hi Chaitanya

    I don’t think that your 2nd point for similarity is correct. I have created the Hashset and added some items into it and then converted it to Treeset the result was unsorted list.Below is the code let me know if i am wrong

    public static void main(String[] args) {
    // Create a HashSet
    HashSet hset = new HashSet();

    //add elements to HashSet
    hset.add(“Steve”);
    hset.add(“Matt”);
    hset.add(“Govinda”);
    hset.add(“John”);
    hset.add(“Tommy”);

    // Displaying HashSet elements
    System.out.println(“HashSet contains: “+ hset);

    // Creating a List of Treeset elements
    TreeSet list = new TreeSet(hset);

    // Displaying ArrayList elements
    System.out.println(“TreeSet contains: “+ list);
    }

    THE OUT PUT IS

    HashSet contains: [Tommy, Matt, Steve, Govinda, John]
    TreeSet contains: [Govinda, John, Matt, Steve, Tommy]

    Reply
  3. Anshul says

    October 8, 2016 at 6:17 PM

    Sorry for the confusion for my post . I understood now that treeset sorts the data in ascending order.

    Reply
  4. Prutha says

    March 15, 2017 at 3:45 PM

    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.

    why?

    Reply
    • Pranjali says

      July 28, 2017 at 9:35 AM

      Because 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.

      Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorial

Java Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap