Open In App

Java TreeMap Equivalent in C#

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

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, remove, retrieve).

In C#, the SortedDictionary class is the closest equivalent to Java TreeMap. It is an ordered collection of key-value pairs. SortedDictionary is a generic dictionary where keys are sorted by their natural ordering or by a provided comparer. Like TreeMap, it maintains the key-value pairs in sorted order using a self-balancing binary search tree (mostly like a Red-Black Tree).

Java TreeMap vs C# SortedDictionary

Features

Java TreeMap

C# SortedDictionary

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 TreeMap. The SortedDictionary<TKey, TValue> class provides similar functionality, but Java's TreeMap includes additional methods like headMap(), tailMap(), and subMap(), which are not directly available in C#.

Key Features of SortedDictionary:

  • The keys are always sorted in ascending order by default, or according to a custom comparer.
  • This ensures that all keys in the dictionary are unique means there are no duplicates.
  • It provides O(log n) time complexity for insertions and deletions.
  • It stores data in key-value pairs like a dictionary.

Usage of SortedDictionary<TKey, TValue> in C#

Below is a simple example that demonstrates how to use SortedDictionary<TKey, TValue> in C#:

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

class Geeks {
    static void Main()
    {
        // Creating a SortedDictionary with
        // string keys and int values
        SortedDictionary<string, int> sd
            = new SortedDictionary<string, int>();

        // Adding elements
        sd.Add("Geek1", 1);
        sd.Add("Geek2", 2);
        sd.Add("Geek3", 3);

        // Iterating through the dictionary
        Console.WriteLine("SortedDictionary elements:");
        foreach(KeyValuePair<string, int> kvp in sd)
        {
            Console.WriteLine(
                $"Key: {kvp.Key}, Value: {kvp.Value}");
        }

        // Checking if a key exists
        if (sd.ContainsKey("Geek2")) {
            Console.WriteLine("Key 'Geek2' exists.");
        }

        // Removing an element
        sd.Remove("Geek2");
        Console.WriteLine("After removing 'Geek2':");
        foreach(KeyValuePair<string, int> kvp in sd)
        {
            Console.WriteLine(
                $"Key: {kvp.Key}, Value: {kvp.Value}");
        }
    }
}

Output
SortedDictionary elements:
Key: Geek1, Value: 1
Key: Geek2, Value: 2
Key: Geek3, Value: 3
Key 'Geek2' exists.
After removing 'Geek2':
Key: Geek1, Value: 1
Key: Geek3, Value: 3


Custom Sorting with IComparer<TKey>

When we want to sort the keys in a custom order, we can use an IComparer<TKey> implementation at the time of creation of the SortedDictionary.

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

class Geeks {
    static void Main()
    {
        // Custom comparer for descending order
        SortedDictionary<string, int> sd
            = new SortedDictionary<string, int>(
                new DescendingComparer());

        sd.Add("Geek1", 1);
        sd.Add("Geek2", 2);
        sd.Add("Geek3", 3);

        Console.WriteLine(
            "SortedDictionary with custom comparer (descending order):");
        foreach(KeyValuePair<string, int> kvp in sd)
        {
            Console.WriteLine(
                $"Key: {kvp.Key}, Value: {kvp.Value}");
        }
    }
}

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

Output
SortedDictionary with custom comparer (descending order):
Key: Geek3, Value: 3
Key: Geek2, Value: 2
Key: Geek1, Value: 1


Dictionary Operations

The SortedDictionary supports basic dictionary operations such as adding, removing, and updating key-value pairs.

Example:

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

class Geeks {
    static void Main()
    {
        SortedDictionary<string, int> sd
            = new SortedDictionary<string, int>();

        // Adding elements
        sd.Add("Geek1", 1);
        sd.Add("Geek2", 2);
        sd["Geek3"] = 3;

        // Updating an element
        sd["Geek2"] = 5;

        // Iterating through the dictionary
        Console.WriteLine("Updated SortedDictionary:");
        foreach(KeyValuePair<string, int> kvp in sd)
        {
            Console.WriteLine(
                $"Key: {kvp.Key}, Value: {kvp.Value}");
        }
    }
}

Output
Updated SortedDictionary:
Key: Geek1, Value: 1
Key: Geek2, Value: 5
Key: Geek3, Value: 3


Thread Safety

SortedDictionary in C# is not thread-safe like Java TreeMap. But if we want thread-safe operations, we can use synchronization mechanisms such as locks or can use ConcurrentDictionary.


Next Article
Article Tags :

Similar Reads