Java - Differences Between HashSet and TreeSet

HashSet vs TreeSet in Java: Here, we are going to learn what are the differences between the HashSet and TreeSet in Java programming language? By Preeti Jain Last updated : March 25, 2024

What is HashSet in Java?

HashSet is an implementation of the Set interface that uses a hash table for storage. It does not guarantee the order of its elements. HashSet permits the null element and is not synchronized, which means that we can add a null value to a HashSet.

Why do we use HashSet in Java?

Well, there are many use cases for Hashset. Some common use cases are as follows-

  • If you have a list of elements and you want to eliminate duplicate values, HashSet is an excellent choice.
  • When you need to quickly check whether a particular element exists in a collection or not, HashSet offers constant-time performance for the contains() operation,
  • HashSet can be used to maintain a cache of unique elements in memory. This is especially useful when dealing with large datasets where you need to quickly check whether an element has been encountered before.
  • If you need to represent a mathematical set in your program, HashSet is an ideal choice.
  • HashSet is efficient for handling large volumes of data.

Java HashSet Example 1

// Java program to demonstrate the behavior of HashSet

import java.util.*;

class HashSetClass {
  public static void main(String[] args) {
    // Creating an instance of HashSet
    HashSet hs = new HashSet();

    // By using add() method to add elements in HashSet
    hs.add(10);
    hs.add(30);
    hs.add(40);
    hs.add(20);

    // Here we will not get any exception because 
    // null insertion is possible in HashSet
    hs.add(null);

    // Here will not get any exception or errors 
    // but it will be ignored because duplicate insertion
    // is not possible 
    hs.add(30);

    // Here we will not get any exception because hetrogenous 
    // object insertion is possible in HashSet
    hs.add("Java");

    // Display Current HashSet
    System.out.println("Current HashSet is :" + hs);
  }
}

Output

E:\Programs>javac HashSetClass.java

E:\Programs>java HashSetClass
Current HashSet is :[null, 20, 40, 10, Java, 30]

Java HashSet Example 2

import java.util.HashSet;

public class HashSetExample {
  public static void main(String[] args) {
    HashSet < String > names = new HashSet < > ();
    names.add("Shyam");
    names.add("Rubina");
    names.add("Rohan");
    names.add(null); // HashSet permits null elements
    names.add("Reshma"); // Adding a duplicate element, it will be ignored

    // Print HashSet
    System.out.println("HashSet: " + names);
  }
}

Output

HashSet: [null, Rubina, Shyam, Reshma, Rohan]

In this example, we create a HashSet called names to store strings. We add a few strings to it and also add a null value. Note that HashSet permits null elements. When we print the HashSet, we see that the elements are not in the order of insertion, as HashSet does not guarantee any specific order.

What is TreeSet in Java?

TreeSet is also an implementation of the Set interface but uses a self-balancing binary search tree (specifically, a Red-Black tree) for storage. TreeSet sorts its elements in ascending order by default. TreeSet does not permit null elements and is not synchronized, which means that we can't add a null value in a TreeSet.

Why do we use TreeSet in Java?

  • TreeSet automatically sorts its elements in ascending order. So, if you have a collection of elements that you need to keep sorted, TreeSet provides a convenient way.
  • Similar to HashSet, TreeSet make sure that each element is unique. 
  • TreeSet provides methods like headSet(), tailSet(), and subSet() that allow you to perform range queries efficiently. 
  • TreeSet offers methods like higher(), lower(), ceiling(), and floor() that allow you to check the elements of the set based on their values. 
  • TreeSet can implement priority queues, where elements are stored in sorted order based on their natural ordering or a custom comparator. 

Java TreeSet Example 1

// Java program to demonstrate the behavior of TreeSet

import java.util.*;

class TreeSetClass {
  public static void main(String[] args) {
    // Creating an instance of TreeSet
    TreeSet ts = new TreeSet();

    // By using add() to add elements in TreeSet
    ts.add(10);
    ts.add(30);
    ts.add(40);
    ts.add(20);

    // ts.add(30); 
    // Here will not get any exception or errors 
    // but it will be ignored because duplicate 
    // insertion is not possible */

    // ts.add(null); 
    // here we will get an exception NullPointerException 
    // because we are inserting null for non-empty set */

    // ts.add("Java"); 
    // here we will get an exception ClassCastException 
    // because we are inserting hetrogenous object in TreeSet */

    // Display Current TreeSet
    System.out.println("Current TreeSet is :" + ts);
  }
}

Output

E:\Programs>javac TreeSetClass.java

E:\Programs>java TreeSetClass
Current TreeSet is :[10, 20, 30, 40]

Java TreeSet Example 2

import java.util.TreeSet;

public class TreeSetExample {
  public static void main(String[] args) {
    TreeSet < Integer > numbers = new TreeSet < > ();
    numbers.add(1);
    numbers.add(3);
    numbers.add(5);
    numbers.add(7);
    numbers.add(9);

    int nextGreaterOrEqual = numbers.ceiling(6);
    System.out.println("Next greater or equal element to 6: " + nextGreaterOrEqual);

  }
}

Output

Next greater or equal element to 6: 7

Difference Between HashSet and TreeSet in Java

The following tables shows the main differences between HashSet and TreeSet in Java:

Feature HashSet TreeSet
Ordering HashSet has no specific order. TreeSet elements are sorted in ascending order by default.
Implementation HashSet uses hash table. TreeSet uses Red-Black tree.
Null elements HashSet displays null element. TreeSet does not display null elements.
Duplicates HashSet ignores duplicate elements. TreeSet ignores duplicate elements.
Performance HashSet is generally faster. TreeSet is slower due to sorting.
Use of Comparator HashSet doesn't require a Comparator. TreeSet can use a Comparator for custom ordering.
Iteration order HashSet is unpredictable. TreeSet follows sorted order.
Memory consumption HashSet requires less memory. TreeSet requires more memory.
Retrieval of elements HashSet has O(1) average case. TreeSet has O(log n) time complexity.
Use cases Usage of HashSet is general-purpose. TreeSet is used when elements need sorting or ordered collection.


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.