Difference and similarities between HashSet, LinkedHashSet and TreeSet in Java
Last Updated : 12 Aug, 2022
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(); } }
OutputInsertion 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:
- HashSet: If you don’t want to maintain insertion order but want to store unique objects.
- LinkedHashSet: If you want to maintain the insertion order of elements then you can use LinkedHashSet.
- 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.
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