Open In App

Java TreeSet Equivalent in C#

Last Updated : 20 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Java, TreeSet is one of the most important implementations of the SortedSet interface based on a Tree (red-black tree) as a data storage. The elements are sorted by a set using their natural order whether an explicit comparator is provided or not.

In C#, the SortedSet class is the closest equivalent to Java TreeSet. It is an ordered set of unique elements. SortedSet is a generic set with unique elements ordered by the natural ordering of the element or by an implemented comparer. Like TreeSet, it keeps the elements in sorted order using a self-balancing binary search tree (mostly like a red-black tree).

Java TreeSet vs C# SortedSet

Features

Java TreeSet

C# SortedSet

Data Structure

Red-Black Tree

Red-Black Tree

Sorting

This is sorted by natural order or custom comparator.

This is sorted by natural order or custom comparer.

Time Complexity

O(log n)

O(log n)

Duplicates

It does not contain any duplicate element.

It also does not contain any duplicate elements.

Thread Safety

Not thread-safe.

Not thread-safe.

Note: C# does not have a built-in equivalent of Java’s TreeSet. The SortedSet class provides similar functionality, but Java's TreeSet has additional methods like headSet(), tailSet(), and subSet(), which are not directly available in C#.

Key Features of SortedSet:

  • The elements are always sorted in ascending order by default, or according to a custom comparer.
  • This ensures that all elements in the set are unique means there are no duplicates.
  • It provides O(log n) time complexity for insertions and deletions.
  • It supports standard set operations like union, intersection, and difference.

Usage of SortedSet in C#

Below is a simple example that demonstrates how to use SortedSet<T> in C#:

C#
// Demonstrating SortedSet in C#
using System;
using System.Collections.Generic;

class Geeks
{
    static void Main()
    {
        // creating a SortedSet 
        // with integer elements
        SortedSet<int> ss = new SortedSet<int>();

        // Adding elements
        ss.Add(6);
        ss.Add(4);
        ss.Add(2);
        ss.Add(1);

        // Iterating through the set
        Console.WriteLine("SortedSet elements:");
        foreach (int e in ss)
        {
            Console.WriteLine(e);
        }

        // Checking if an element exists
        if (ss.Contains(2))
        {
            Console.WriteLine("Element 2 exists.");
        }

        // Removing an element
        ss.Remove(6);
        Console.WriteLine("After removing 6:");
        foreach (int e in ss)
        {
            Console.WriteLine(e);
        }
    }
}

Output
SortedSet elements:
1
2
4
6
Element 2 exists.
After removing 6:
1
2
4


Custom Sorting with IComparer<T>

When we want to sort the elements in a custom order, we can use an IComparer<T> implementation at the time of creation of SortedSet.

Example:

C#
// Demonstrating Custom Sorting 
using System;
using System.Collections.Generic;

class Geeks
{
    static void Main()
    {
        // Custom comparer for descending order
        SortedSet<int> ss = new SortedSet<int>(new DescendingComparer());

        ss.Add(6);
        ss.Add(4);
        ss.Add(2);
        ss.Add(1);

        Console.WriteLine("SortedSet with custom comparer (descending order):");
        foreach (int e in ss)
        {
            Console.WriteLine(e);
        }
    }
}

class DescendingComparer : IComparer<int>
{
    public int Compare(int x, int y)
    {
        return y.CompareTo(x); 
    }
}

Output
SortedSet with custom comparer (descending order):
6
4
2
1


Set Operations

The SortedSet supports basic set operations such as union, intersection, and difference.

Example:

C#
// Basic Set operations
using System;
using System.Collections.Generic;

class Geeks
{
    static void Main()
    {
        SortedSet<int> s1 = new SortedSet<int> { 1, 2, 3, 4 };
        SortedSet<int> s2 = new SortedSet<int> { 2, 3, 7, 8 };

        // Union
        SortedSet<int> u = new SortedSet<int>(s1);
        u.UnionWith(s2);
        Console.WriteLine("Union:");
        foreach (int e in u)
        {
            Console.WriteLine(e);
        }

        // Intersection
        SortedSet<int> i = new SortedSet<int>(s1);
        i.IntersectWith(s2);
        Console.WriteLine("Intersection:");
        foreach (int e in i)
        {
            Console.WriteLine(e);
        }

        // Difference
        SortedSet<int> d = new SortedSet<int>(s1);
        d.ExceptWith(s2);
        Console.WriteLine("Difference:");
        foreach (int e in d)
        {
            Console.WriteLine(e);
        }
    }
}

Output
Union:
1
2
3
4
7
8
Intersection:
2
3
Difference:
1
4


Thread Safety

SortedSet in C# is not thread safe like Java TreeSet. But if we want thread-safe operations, we can use synchronization mechanisms like locks or we can use ConcurrentDictionary<TKet, TValue> with dummy values.


Next Article
Article Tags :

Similar Reads