Let’s first discuss the key points about TreeSet and LinkedHashSet in Java:

Underlying Data Structure:

  • TreeSet: Based on a Red-Black Tree (a self-balancing Binary Search Tree).
  • LinkedHashSet: Backed by a HashMap and a linked list (the latter helps in maintaining the order of insertion).

Ordering:

  • TreeSet: Elements are stored in a sorted order based on their natural ordering (if they implement Comparable) or by a provided Comparator.
  • LinkedHashSet: Elements are stored in the order of their insertion.

Performance:

  • TreeSet: Offers O(log n) time for most operations like add, remove, and contains due to the tree structure.
  • LinkedHashSet: Generally provides O(1) time performance for add, remove, and contains, assuming the hash function disperses the elements properly among the buckets.

Null Elements:

  • TreeSet: Only allows one null element, but only if no comparator is used (i.e., relying on natural ordering). If a custom comparator is provided, it should be able to handle null.
  • LinkedHashSet: Allows one null element.

Iterators:

  • TreeSet: The iterator goes through elements in ascending (sorted) order.
  • LinkedHashSet: The iterator goes through elements in their order of insertion.

Implementation:

  • TreeSet: Implements the NavigableSet interface, giving it navigation methods like lower(), floor(), ceiling(), and higher().
  • LinkedHashSet: Extends HashSet and implements the Set interface, so it doesn’t have navigation methods.

Memory Overhead:

  • TreeSet: Typically has more overhead than a simple set due to the storage requirements of the tree structures.
  • LinkedHashSet: Has additional overhead due to maintaining the linked list to preserve insertion order.

Concurrency:

  • Neither is thread-safe. If needed in a concurrent scenario, external synchronization or concurrent collections should be used.

Usage Scenarios:

  • TreeSet: When you need a set with unique elements that are always in a sorted order.
  • LinkedHashSet: When you need a set with unique elements and also want to maintain the order of insertion.

Difference Between TreeSet and LinkedHashSet in Java

Criteria TreeSet LinkedHashSet
Underlying Data Structure Red-Black Tree (balanced binary search tree) Hash table + Linked list
Ordering of Elements Ordered based on natural ordering or custom comparator Maintains the insertion order
Performance Add, Remove, Contains: O(log n) Add: O(1) on average, but can be O(n) in worst case
Remove, Contains: O(1)
Null Elements Does not allow null if natural ordering is used or if custom comparator does not support it Allows one null element
Interfaces Implemented Set, NavigableSet, SortedSet Set
Duplicates Does not allow duplicates Does not allow duplicates
Use-case When you need to store elements in a sorted order and need operations like higher() or lower() When you want to maintain the order of insertion and have faster access, insert, and delete operations

Example: Difference Between TreeSet and LinkedHashSet in Java

import java.util.LinkedHashSet;
import java.util.Set;
import java.util.TreeSet;

public class TreeSetVsLinkedHashSetDemo {

    public static void main(String[] args) {

        // Create a LinkedHashSet and add elements
        Set<String> linkedHashSet = new LinkedHashSet<>();
        linkedHashSet.add("Cherry");
        linkedHashSet.add("Banana");
        linkedHashSet.add("Apple");

        System.out.println("LinkedHashSet:");
        for (String item : linkedHashSet) {
            System.out.println(item);
        }

        // Create a TreeSet and add elements
        Set<String> treeSet = new TreeSet<>();
        treeSet.add("Cherry");
        treeSet.add("Banana");
        treeSet.add("Apple");

        System.out.println("\nTreeSet:");
        for (String item : treeSet) {
            System.out.println(item);
        }
    }
}

Output:

LinkedHashSet:
Cherry
Banana
Apple

TreeSet:
Apple
Banana
Cherry

Explanation:

1. LinkedHashSet: The LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked list of all elements. It ensures that the elements remain in the order in which they were inserted. Therefore, the iteration order is predictable.

2. TreeSet: The TreeSet is a NavigableSet implementation backed by a TreeMap. It is sorted by natural ordering, or by a comparator provided at set creation time, if specified. Therefore, when you iterate over a TreeSet, it will provide elements in ascending order (for the natural order).

3. In the provided example, both the LinkedHashSet and TreeSet have the entries "Cherry", "Banana", and "Apple" added. In the LinkedHashSet, the output is in the order they were inserted, which is "Cherry", "Banana", "Apple". However, in the TreeSet, the output is in their natural order, which for strings is lexicographical order, resulting in "Apple", "Banana", "Cherry".

4. When the requirement is to maintain the insertion order of elements, LinkedHashSet should be used. When the elements need to be sorted by their natural order or by a provided comparator, TreeSet should be chosen.