The Java HashMap class has no concrete identical in C#. Yet, the Dictionary<TKey, TValue> class offered by the.NET framework is the principal replacement for the Java HashMap in C# and may be used to accomplish the same functionality. We will discuss about C# alternatives for Java HashMap using code snippets.
Example 1: Dictionary<TKey, TValue>
The C# Dictionary<TKey, TValue> serves as a powerful alternative to the Java HashMap for mapping keys to values efficiently. The given C# code demonstrates the usage of the Dictionary<TKey, TValue> step by step. The code begins with importing the necessary namespaces which include the System and System.Collections.Generic. These namespaces provide access to essential C# classes and data structures.
The Dictionary<string, int> called “dic” is instantiated. It stores the string keys (representing subjects) and integer values (representing marks). Three key-value sets are saved to the “dic” dictionary. Subjects (keys) such as “Math,” “Eng”, and “Comp” are mapped to their respective marks (values) which are 30, 25, and 22. The code retrieves the mark that is associated with the “Eng” subject and assigns it to the “mark” variable. It then prints the result which displays “Eng’s mark: 25”.
The code checks whether the “Math” key occurs in the dictionary via the ContainsKey method. Since “Math” is present, it prints “Math’s mark exists”. The code uses a “foreach” loop to go through every key-value set in the “dic” dictionary. For each pair, it prints the subject (key) followed by its associated mark (value).
using System.Collections.Generic;
class Dummy {
static void Main() {
Dictionary<string, int> dic = new Dictionary<string, int>();
dic["Math"] = 30;
dic["Eng"] = 25;
dic["Comp"] = 22;
int mark = dic["Eng"];
Console.WriteLine($"Eng's mark: {mark}");
if (dic.ContainsKey("Math")) {
Console.WriteLine("Math's mark exists.");
}
foreach (KeyValuePair<string, int> p in dic) {
Console.WriteLine($"{p.Key}: {p.Value}");
}
}
}
The output demonstrates adding the key-value pairs, retrieving the values, checking the key existence, and iterating through the dictionary as follows:
Example 2: SortedDictionary<int, string>
The SortedDictionary<int, string> class is also used as an alternative to Java’s HashMap. The following code starts by creating a SortedDictionary<int, string> named “Price” which maps the integer keys (representing the prices) to string values (representing the product names). Unlike the Java HashMap, the SortedDictionary maintains the keys in sorted order.
The code then adds three key-value pairs to the “Price” dictionary. The prices of three beauty products – Blush, Mascara, and Lipstick – are associated with their respective names. Next, the code uses LINQ (Language-Integrated Query) to find the most expensive product by retrieving the maximum key from the dictionary. The Price.Keys.Max() function returns the ultimate price (key) among the available products.
After finding the most expensive product’s price, the code uses that price as the key to retrieve the corresponding product name from the “Price” dictionary. The code then prints the most expensive product’s price using string interpolation ($”Most Expensive: ${Exp}”). It also iterates through the entire dictionary using a foreach loop to print each product name along with its price.
using System.Collections.Generic;
using System.Linq;
class Dummy {
static void Main() {
SortedDictionary<int, string> Price = new SortedDictionary<int, string>();
Price[90] = "Blush";
Price[85] = "Mascara";
Price[95] = "Lipstick";
int Exp = Price.Keys.Max(); //LINQ's Max method to find the maximum key
string Expr = Price[Exp];
Console.WriteLine($"Most Expensive: ${Exp}");
foreach (KeyValuePair<int, string> p in Price) {
Console.WriteLine($"{p.Value}: ${p.Key}");
}
}
}
Overall, the following output showcases the use of the SortedDictionary<TKey, TValue> class as an alternative to Java’s HashMap to store and retrieve the key-value pairs, maintaining the keys in sorted order. The LINQ method is used to find the most expensive product by obtaining the maximum key from the dictionary:
Example 3: ConcurrentDictionary<TKey, TValue>
Another alternative for Java Hashmap in C# is the ConcurrentDictionary<TKey, TValue> class in a multi-threaded scenario. First, the following code imports necessary namespaces: System, System.Collections.Concurrent, and System.Threading.Tasks. The ConcurrentDictionary<string, double> named “Trip” is created to store the data related to trip expenses where each key is a person’s name (string) and the value is their corresponding budget (double). The budgets of three people – “John”, “Tom”, and “Ana” – are added to the “Trip” ConcurrentDictionary.
The “Parallel.Invoke” method is used to perform the concurrent updates to the “Trip” dictionary. Three separate threads are created to update the budgets of “John”, “Tom”, and “Ana”, concurrently. This demonstrates the thread-safety feature of ConcurrentDictionary which allows multiple threads to modify the dictionary concurrently without causing conflicts or data corruption. The “update” method takes three parameters: the person’s name, the budget change, and the ConcurrentDictionary<string, double> dic that stores the trip data.
In this method, the budget of the specified person is updated by adding the provided budget change value. After the concurrent updates are completed, the code prints the updated trip expenses for each person using a foreach loop. It iterates through the “Trip” dictionary and displays the name and budget of each person.
using System.Collections.Concurrent;
using System.Threading.Tasks;
class Test {
static void Main() {
ConcurrentDictionary<string, double> Trip = new ConcurrentDictionary<string, double>();
Trip["John"] = 1000.0;
Trip["Tom"] = 930.0;
Trip["Ana"] = 5000.0;
Parallel.Invoke(
() => update("John", 500.0, Trip),
() => update("Tom", -30.0, Trip),
() => update("Ana", -20.0, Trip)
);
foreach (var p in Trip) {
Console.WriteLine($"{p.Key}: {p.Value}");
}
}
static void update(string title, double budget, ConcurrentDictionary<string, double> dic) {
dic[title] += budget;
}
}
The result for the previous code is displayed as follows:
Example 4: HashSet<T>
The usage of the HashSet<T> class also serves as an alternative to the Java HashMap when you need to store a collection of unique elements without associated values. It automatically handles duplicates, ensuring that only the distinct values are stored. The code example includes the necessary using directives for working with collections, particularly with HashSet<T>.
Inside “Main”, a new HashSet<int> named “Unique” is created to store the unique integers. Four integers – 44, 65, 88, and 65 – are added to the “Unique” set using the “Add” method. Note that adding the second occurrence of 65 does not introduce any duplicates since HashSet<T> ensures uniqueness. The code then checks whether the number 88 exists in the set using the “Contains” method.
Since 88 was added to the set earlier, the condition evaluates to true, and the “Number 88 exists in the set” statement is printed to the console. The code utilizes a foreach loop to iterate through the elements of the “Unique” set. The loop prints each unique integer that is stored in the set (44, 65, and 88) on separate lines.
using System.Collections.Generic;
class Test {
static void Main() {
HashSet<int> Unique = new HashSet<int>();
Unique.Add(44);
Unique.Add(65);
Unique.Add(88);
Unique.Add(65);
if (Unique.Contains(88)) {
Console.WriteLine("Number 88 exists in the set.");
}
foreach (int v in Unique) {
Console.WriteLine(v);
}
}
}
By utilizing HashSet<T>, the provided code effectively stores the unique integers and iterates through the collection without encountering any duplicates. This makes HashSet<T> a suitable alternative to Java’s HashMap when the requirement is to manage the collections of unique elements:
Conclusion
Both Java HashMap and its C# equivalents offer effective solutions for mapping keys to values. Although the Java Collections Framework’s Java HashMap is a basic component, C# has several alternatives that are used in this guide including the Dictionary<TKey, TValue>, SortedDictionary<TKey, TValue>, ConcurrentDictionary<TKey, TValue>, and Hash<SetT>. Each approach tackles a certain requirement which renders them with worthwhile selections based on the particular requirements of the application.