Solidity is an object-oriented language designed for the Ethereum blockchain to facilitate smart contract development. It offers a wide range of data structure support, including HashMap.
HashMap, sometimes referred to as a Dictionary, is a key-value-based data structure that maps values against unique/non-repeating keys. Additionally, it allows constant look-up time on average due to the nature of its implementation.
Unlike other programming languages (C++, JavaScript), Solidity does not provide a way to directly access the keys of a HashMap. However, we can explicitly maintain a dynamic array that keeps hold of all the keys and an additional HashMap to check whether the key exists.
pragma solidity ^0.5.0;// Defining contractcontract Persons {// For storing keysuint[] _ids;// Main Map for storing datamapping (uint => string) _names;// Additional Map for checking if key existsmapping (uint => bool) _exists;function setPerson(uint id, string memory name) public {// if key does not exist then insert in arrayif (!_exists[id]) {_ids.push(id);_exists[id] = true;}// insert/update main map_names[id] = name;}function getKeys() public view returns(uint[] memory){return _ids;}}
Note: Array
_ids
type and the additional HashMap_exists
key type should be same as the key type of the main HashMap_names
.
Line 4: We define a contract.
Line 7: We declare a dynamic array to store the keys.
Line 10: We declare the main HashMap that will hold the significant data.
Line 13: We declare an additional HashMap to check if a value already exists against a particular key.
Line 15: We create a utility function to insert/update the main HashMap _names
. The function checks if the key was previously present or not. If not inserted previously, it adds the key inside the array _ids
and updates the additional HashMap _exists
against that key. In the end, it simply adds or updates the value against the key supplied.
Line 27: We create a read-only/view function that returns the array _ids
holding all the keys.