Difference and similarities between HashSet, LinkedHashSet and TreeSet in Java

In this article we will learn, Difference between HashSet vs LinkedHashSet and TreeSet And similarities between LinkedHashSet and TreeSet. HashSet, LinkedHashSet and TreeSet all implementations of Set interface, there are some differences and similarities exist between them. 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 store unique objects If you want to maintain 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 insertion order of objects While TreeSet orders of the elements according to supplied Comparator. Default, It’s objects will be placed in their natural ascending order.
Complexity of Operations HashSet gives O(1) complicity for insertion, removing and retrieving objects LinkedHashSet gives insertion, removing and retrieving operations performance in order O(1). While TreeSet gives performance of order O(log(n)) for insertion, removing and retrieving operations.
Performance HashSet performance is better according to LinkedHashSet and TreeSet. The performance of LinkedHashSet is slow to TreeSet. The performance LinkedHashSet is almost similar to HashSet but slower because, LinkedHashSet maintains LinkedList internally to maintain the insertion order of elements TreeSet performance is better to LinkedHashSet excluding insertion and removal operations because, it has to sort the elements after each insertion and removal operations.
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 objects LinkedHashSet allows only one null objects. TreeSet not allow a any null objects. If you insert null objects into TreeSet, it throws 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:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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
        // storeds 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 sec : "
                           + (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 in sec : "
                           + (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 sec : "
                           + (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 sec : "
                           + 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 sec : "
                           + 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 sec : "
                           + Math.abs(startingTime - endedTime));
    }
  
    public static void main(String args[])
    {
  
        insertionOrder();
        insertionTime();
        deletion();
    }
}

chevron_right


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 sec : 3752794
Total time to insert 1000 elements in LinkedHashSet in sec : 1293794
Total time to insert 1000 elements in TreeSet in sec : 8073353
Total time to Deletion 1000 elements in HashSet in sec : 848690
Total time to Deletion 1000 elements in LinkedHashSet in sec : 937622
Total time to Deletion 1000 elements in TreeSet in sec : 3346092

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 multi-threading environment then first we make it externally synchronize 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 store unique objects.
LinkedHashSet: If you want to maintain 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 output above program according that and according your requirements you can choose any one from HashSet, TreeSet and LinkedHashSet.



My Personal Notes arrow_drop_up

Strategy Path planning and Destination matters in success No need to worry about in between temporary failures

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.