Java TreeSet Equivalent in C#
Last Updated :
20 Mar, 2025
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);
}
}
}
OutputSortedSet 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);
}
}
OutputSortedSet 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);
}
}
}
OutputUnion:
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.
Similar Reads
Java TreeMap Equivalent in C# In Java, TreeMap is a part of the Collection Framework. It implements the Map and NavigableMap interface and extends the AbstarctMap class. It stores key-value pairs in a sorted order based on the natural ordering of keys or a custom Comparator. It uses a Red-Black Tree for efficient operations (add
4 min read
C# | Add element to SortedSet SortedSet class represents the collection of objects in sorted order. This class comes under the System.Collections.Generic namespace. SortedSet.Add(T) Method is used to add an element to the set and returns a value that specify if it was successfully added or not. Properties: In C#, SortedSet class
2 min read
C# | Remove the specified element from a HashSet A HashSet is an unordered collection of the unique elements. It comes under System.Collections.Generic namespace. It is used in a situation where we want to prevent duplicates from being inserted in the collection. As far as performance is concerned, it is better in comparison to the list. HashSet
3 min read
C# | Remove all elements from the SortedSet SortedSet class represents the collection of objects in sorted order. This class comes under the System.Collections.Generic namespace. SortedSet<T>.Clear Method is used to remove the all elements from the SortedSet. Properties: In C#, SortedSet class can be used to store, remove or view elements.
2 min read
C# | Get the number of elements in the SortedSet SortedSet class represents the collection of objects in sorted order. This class comes under the System.Collections.Generic namespace. SortedSet<T>.Count Property is used to get the number of elements in the SortedSet. Properties: In C#, SortedSet class can be used to store, remove or view elemen
2 min read
C# | Add element to HashSet A HashSet is an unordered collection of the unique elements. It comes under System.Collections.Generic namespace. It is used in a situation where we want to prevent duplicates from being inserted in the collection. As far as performance is concerned, it is better in comparison to the list. Elements
2 min read
C# | Check if two SortedSet<T> objects are equal Equals(Object) Method which is inherited from the Object class is used to check if a specified SortedSet<T> object is equal to another SortedSet<T> object or not. Syntax: public virtual bool Equals (object obj); Here, obj is the object which is to be compared with the current object. Ret
2 min read
C# | Intersection of two HashSets A HashSet is an unordered collection of the unique elements. It is found in System.Collections.Generic namespace. It is used in a situation where we want to prevent duplicates from being inserted in the collection. As far as performance is concerned, it is better in comparison to the list. HashSet.I
3 min read
C# | Stack<T>.TrimExcess Method with Examples Stack represents a last-in, first out collection of object. It is used when you need a last-in, first-out access to items. When you add an item in the list, it is called pushing the item and when you remove it, it is called popping the item. Stack<T>.TrimExcess Method is used to set the capacity
2 min read
C# | Remove all elements from a HashSet A HashSet is an unordered collection of the unique elements. It comes under the System.Collections.Generic namespace. It is used in a situation where we want to prevent duplicates from being inserted in the collection. As far as performance is concerned, it is better in comparison to the list. HashS
2 min read