Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
LinkedHashMap and LinkedHashSet in Java
Next article icon

Difference and similarities between HashSet, LinkedHashSet and TreeSet in Java

Last Updated : 12 Aug, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will learn, the difference between HashSet vs LinkedHashSet and TreeSet And similarities between LinkedHashSet and TreeSet. HashSet, LinkedHashSet, and TreeSet all implement the Set interface. So we have tried to list out the differences and similarities between HashSet, LinkedHashSet, and TreeSet in java.

Differences Between HashSet, LinkedHashSet, and TreeSet: 

Features

HashSet

LinkedHashSet

TreeSet

Internal Working

HashSet internally uses HashMap for storing objects

LinkedHashSet uses LinkedHashMap internally to store objects

TreeSet uses TreeMap internally to store objects

When To Use

If you don’t want to maintain insertion order but want to store unique objects

If you want to maintain the insertion order of elements then you can use LinkedHashSet

If you want to sort the elements according to some Comparator then use TreeSet

Order

HashSet does not maintain insertion order

LinkedHashSet maintains the insertion order of objects

While TreeSet orders the elements according to supplied Comparator. By default, objects will be placed according to their natural ascending order.

Complexity of Operations

HashSet gives O(1) complexity for insertion, removing, and retrieving objects

LinkedHashSet gives insertion, removing, and retrieving operations performance in order O(1).

While TreeSet gives the performance of order O(log(n)) for insertion, removing, and retrieving operations.

Performance

The performance of HashSet is better when compared to LinkedHashSet and TreeSet.

The performance of LinkedHashSet is slower than TreeSet. It is almost similar to HashSet but slower because LinkedHashSet internally maintains LinkedList to maintain the insertion order of elements

TreeSet performance is better than LinkedHashSet except for insertion and removal operations because it has to sort the elements after each insertion and removal operation.

Compare

HashSet uses equals() and hashCode() methods to compare the objects

LinkedHashSet uses equals() and hashCode() methods to compare it's objects

TreeSet uses compare() and compareTo() methods to compare the objects

Null Elements

HashSet allows only one null value.

LinkedHashSet allows only one null value.

TreeSet does not permit null value. If you insert null value into TreeSet, it will throw NullPointerException.

Syntax

HashSet obj = new HashSet();

LinkedHashSet obj = new LinkedHashSet();

TreeSet obj = new TreeSet();


Differences Between HashSet, LinkedHashSet, and TreeSet According to Insertion Order and Time Taken:
 

Java
// Java program to demonstrate difference between // HashSet, LinkedHashSet and TreeSet according  // to insertion order and insertion time  import java.util.Arrays; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.TreeSet;  class GFG1 {     // Function show insertion order of     // LinkedHashSet, TreeSet and HashSet      private static void insertionOrder()     {         LinkedHashSet<String> geekLinkSet             = new LinkedHashSet<>();         TreeSet<String> geekTreeSet = new TreeSet<>();         HashSet<String> geekHashSet = new HashSet<String>();          // Add three object in         // LinkedHashSet and TreeSet         for (String str : Arrays.asList("Geek2", "Geek1",                                         "Geek3", "Geek1")) {              geekLinkSet.add(str);             geekTreeSet.add(str);             geekHashSet.add(str);         }          // should be sorted order HashSet         // stores element in sorted order         System.out.println("Insertion Order"                            + " of objects in HashSet :"                            + geekHashSet);          // insertion order or elements LinkedHashSet         // stores elements as insertion         System.out.println("Insertion Order of "                            + "objects in LinkedHashSet :"                            + geekLinkSet);          // should be sorted order TreeSet         // stores element in sorted order         System.out.println("Insertion Order of"                            + " objects in TreeSet :"                            + geekTreeSet);     }      // Function calculate insertion time of     // 1000 objects of LinkedHashSet,     // TreeSet and HashSet      private static void insertionTime()     {         // HashSet performance Test         // inserting 1000 elements         HashSet<Integer> numbersHS = new HashSet<>();         long startTime = System.nanoTime();         for (int i = 0; i < 1000; i++) {             numbersHS.add(i);         }         long endTime = System.nanoTime();         System.out.println("Total time to insert"                            + " 1000 elements in"                            + " HashSet in nanoseconds: "                            + (endTime - startTime));          // LinkedHashSet performance Test         // inserting 1000 elements         LinkedHashSet<Integer> numbersLLS             = new LinkedHashSet<>();          startTime = System.nanoTime();         for (int i = 0; i < 1000; i++) {             numbersLLS.add(i);         }         endTime = System.nanoTime();         System.out.println("Total time to insert"                            + " 1000 elements in"                            + " LinkedHashSet nanoseconds: "                            + (endTime - startTime));          // TreeSet performance Test inserting 1000 objects         TreeSet<Integer> numbersTS = new TreeSet<>();          startTime = System.nanoTime();         for (int i = 0; i < 1000; i++) {             numbersTS.add(i);         }         endTime = System.nanoTime();         System.out.println("Total time to insert"                            + " 1000 elements in"                            + " TreeSet in nanoseconds: "                            + (endTime - startTime));     }      // Function calculate deletion time     // of 1000 objects LinkedHashSet,     // TreeSet and HashSet     // Deletion time always vary     private static void deletion()     {         // HashSet performance Test inserting         // and deletion 1000 elements         HashSet<Integer> deletionHS = new HashSet<>();          for (int i = 0; i < 1000; i++) {             deletionHS.add(i);         }          long startingTime = System.nanoTime();         for (int i = 0; i < 1000; i++) {             deletionHS.remove(i);         }          long endedTime = System.nanoTime();         System.out.println(             "Total time to Deletion "             + "1000 elements in HashSet in nanoseconds: "             + Math.abs(startingTime - endedTime));          // LinkedHashSet  performance Test inserting         // and deletion 1000 elements         LinkedHashSet<Integer> deletionLLS             = new LinkedHashSet<>();          for (int i = 0; i < 1000; i++) {             deletionLLS.add(i);         }         startingTime = System.nanoTime();         for (int i = 0; i < 1000; i++) {             deletionLLS.remove(i);         }          endedTime = System.nanoTime();         System.out.println(             "Total time to Deletion 1000"             + " elements in LinkedHashSet in nanoseconds: "             + Math.abs(startingTime - endedTime));          // TreeSet performance Test inserting         // and deletion 1000 elements         TreeSet<Integer> deletionTS = new TreeSet<>();          for (int i = 0; i < 1000; i++) {             deletionTS.add(i);         }          startingTime = System.nanoTime();         for (int i = 0; i < 1000; i++) {             deletionTS.remove(i);         }          endedTime = System.nanoTime();         System.out.println(             "Total time to Deletion 1000"             + " elements in TreeSet in nanoseconds: "             + Math.abs(startingTime - endedTime));     }      public static void main(String args[])     {          insertionOrder();         insertionTime();         deletion();     } } 

Output
Insertion Order of objects in HashSet :[Geek3, Geek2, Geek1] Insertion Order of objects in LinkedHashSet :[Geek2, Geek1, Geek3] Insertion Order of objects in TreeSet :[Geek1, Geek2, Geek3] Total time to insert 1000 elements in HashSet in nanoseconds: 791869 Total time to insert 1000 elements in LinkedHashSet nanoseconds: 882417 Total time to insert 1000 elements in TreeSet in nanoseconds: 11797657 Total time to Deletion 1000 elements in HashSet in nanoseconds: 834509 Total time to Deletion 1000 elements in LinkedHashSet in nanoseconds: 898922 Total time to Deletion 1000 elements in TreeSet in nanoseconds: 7437577

Similarities Between HashSet, LinkedHashSet, and TreeSet:

  • Duplicates: HashSet, LinkedHashSet and TreeSet are implements Set interface, so they are not allowed to store duplicates objects.
     
  • Thread-safe: If we want to use HashSet, LinkedHashSet, and TreeSet in a multi-threading environment then first we make it externally synchronized because both LinkedHashSet and TreeSet are not thread-safe. 
     
  • All three are Cloneable and Serializable.

When to use HashSet, TreeSet, and LinkedHashSet in Java: 

  1. HashSet: If you don’t want to maintain insertion order but want to store unique objects. 
  2. LinkedHashSet: If you want to maintain the insertion order of elements then you can use LinkedHashSet. 
  3. TreeSet: If you want to sort the elements according to some Comparator then use TreeSet.

So as you see the output of the above program according to that and according to your requirements, you can choose anyone from HashSet, TreeSet, and LinkedHashSet.


Next Article
LinkedHashMap and LinkedHashSet in Java

R

Rajput-Ji
Improve
Article Tags :
  • Java
  • Technical Scripter
  • Technical Scripter 2018
  • Java-Collections
  • Java - util package
  • java-treeset
  • java-hashset
  • java-LinkedHashSet
  • Java-Set-Programs
Practice Tags :
  • Java
  • Java-Collections

Similar Reads

  • Set in Java
    The Set Interface is present in java.util package and extends the Collection interface. It is an unordered collection of objects in which duplicate values cannot be stored. It is an interface that implements the mathematical set. This interface adds a feature that restricts the insertion of duplicat
    14 min read
  • AbstractSet Class in Java
    In Java, the AbstractSet class is part of the Java Collections Framework. It provides a Skeleton implementation of the set interface, which is a collection that does not allow duplicate elements. This class is abstract, meaning it cannot be instantiated directly, but it can be extended to create a c
    9 min read
  • EnumSet in Java
    In Java, the EnumSet is a specialized set implementation for use with enum types. It is a part of java.util package and provides a highly optimized set for storing enum constants. The EnumSet is one of the specialized implementations of the Set interface for use with the enumeration type. It extends
    9 min read
  • Java HashSet
    HashSet in Java implements the Set interface of Collections Framework. It is used to store the unique elements and it doesn't maintain any specific order of elements. Can store the Null values.Uses HashMap (implementation of hash table data structure) internally.Also implements Serializable and Clon
    12 min read
  • TreeSet in Java
    TreeSet is one of the most important implementations of the SortedSet interface in Java that uses a Tree(red - black tree) for storage. The ordering of the elements is maintained by a set using their natural ordering whether or not an explicit comparator is provided. This must be consistent with equ
    13 min read
  • ConcurrentSkipListSet in Java
    In Java, the ConcurrentSkipListSet is the part of the java.util.concurrent package and provides a scalable, thread-safe alternative to TreeSet. It is a sorted set that lets multiple threads safely access and modify the set at the same time without causing issues. It is thread-safe.Elements are in so
    7 min read
  • CopyOnWriteArraySet in Java
    In Java, the CopyOnWriteArraySet is the part of the java.util.concurrent package and is used to handle thread-safe operations in multi-threaded environments. It is ideal when the set is frequently read but infrequently modified. The set ensures safe access for multiple threads, as it creates a new c
    6 min read
  • Java LinkedHashSet
    LinkedHashSet in Java implements the Set interface of the Collection Framework. It combines the functionality of a HashSet with a LinkedList to maintain the insertion order of elements. Stores unique elements only.Maintains insertion order.Provides faster iteration compared to HashSet.Allows null el
    8 min read
  • Convert HashSet to TreeSet in Java
    Hashset: Hashset in Java is generally used for operations like search, insert and delete. It takes constant time for these operations on average. HashSet is faster than TreeSet. HashSet is Implemented using a hash table. TreeSet: TreeSet in Java takes O(log n) for search, insert and delete which is
    3 min read
  • Difference and similarities between HashSet, LinkedHashSet and TreeSet in Java
    In this article, we will learn, the difference between HashSet vs LinkedHashSet and TreeSet And similarities between LinkedHashSet and TreeSet. HashSet, LinkedHashSet, and TreeSet all implement the Set interface. So we have tried to list out the differences and similarities between HashSet, LinkedHa
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences