beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

Difference between HashSet and TreeSet

By Chaitanya Singh | Filed Under: Java.util package

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

Enjoyed this post? Try these related posts

  1. Convert HashSet to a List/ArrayList
  2. Adding element to front of LinkedList in Java
  3. HashMap – Get value from key example
  4. how to copy one hashmap content to another hashmap
  5. Java – LinkedList peek(), peekFirst() and peekLast() methods
  6. LinkedList push() and pop() methods – Java

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 *

Recently Added..

  • JSON Tutorial
  • Java Regular Expressions Tutorial
  • Java Enum Tutorial
  • Java Annotations Tutorial

Copyright © 2012 – 2021 BeginnersBook . Privacy Policy . Sitemap