How to use Hashmap in TypeScript ?
Last Updated :
10 Apr, 2024
In TypeScript, One can use the built-in Map
data structure to implement a hashmap. A Map
can be used to store key-value pairs where keys can be of any type.
Syntax:
// Create a new empty hashmap
let hashmap: Map<KeyType, ValueType> = new Map();
// Add key-value pairs to the hashmap
hashmap.set(key1, value1);
hashmap.set(key2, value2);
// Get the value associated with a key
let value = hashmap.get(key);
// Check if a key exists in the hashmap
let exists = hashmap.has(key);
// Delete a key-value pair from the hashmap
hashmap.delete(key);
// Total number of key-value pair hashmap contains.
let total = hashMap.size;
//Removes the all key-value pairs from the map() object
hashMap.clear();
Example: Demonstrating HashMap Operations in JavaScript. We set key-value pairs, retrieve values, check key existence, and utilize delete and clear operations.
JavaScript
// Create a new hashmap
let ageMap: Map<string, number> = new Map();
// Add key-value
// pairs to the hashmap
ageMap.set("Alice", 30);
ageMap.set("Bob", 35);
ageMap.set("Charlie", 40);
// Get the value associated with a key
let bobAge = ageMap.get("Bob");
console
.log("Bob's age:", bobAge);
// Output: Bob's age: 35
// Check if a key exists in the hashmap
let hasCharlie = ageMap.has("Charlie");
console
.log("Does Charlie exist?", hasCharlie);
// Output: Does Charlie exist? true
// Delete a key-value pair from the hashmap
ageMap.delete("Charlie");
// Check if Charlie still exists
hasCharlie = ageMap.has("Charlie");
console
.log("Does Charlie still exist?", hasCharlie);
// Output: Does Charlie still exist? false
// Create a new empty hashmap
let hashmap: Map<string, number> = new Map();
// Add key-value pairs to the hashmap
let key1 = "key1";
let value1 = 10;
let key2 = "key2";
let value2 = 20;
hashmap.set(key1, value1);
hashmap.set(key2, value2);
// Get the value associated with a key
let value = hashmap.get(key1);
console
.log("Value for key1:", value);
// Output: Value for key1: 10
// Check if a key exists in the hashmap
let exists = hashmap.has(key2);
console
.log("Does key2 exist?", exists);
// Output: Does key2 exist? true
// Delete a key-value pair from the hashmap
hashmap.delete(key1);
// Total number of key-value
// pairs hashmap contains
let total = hashmap.size;
console
.log("Total number of key-value pairs:", total);
// Output: Total number
// of key-value pairs: 1
// Remove all key-value
// pairs from the hashmap
hashmap.clear();
console
.log("HashMap after clearing:", hashmap);
// Output: HashMap after clearing: Map {}
Output
Bob's age: 35
Does Charlie exist? true
Does Charlie still exist? false
Value for key1: 10
Does key2 exist? true
Total number of key-value pairs: 1
HashMap after clearing: Map(0) {}
Share your thoughts in the comments
Please Login to comment...