HashMap Methods and Usage
- A HashMap can be defined as an 'associate array that stores and retrieves values using hash values for keys, and whose size dynamically increases based on the number of key-value pairs.'
- This associate array is also called a Map, Dictionary, or Symbol Table.
Simply put, it's a fundamentally unordered data structure where keys and values form 1:1 mappings as pairs, and duplicate keys are not allowed.
By default, equals() is used to determine duplicates, so primitive data types are filtered out. However, objects are not filtered out because equals() considers them different even if their values are the same.
Therefore, to prevent duplicate objects, you must override equals().
HashMap Methods #
HashMap Constructor #
Basically, primitive data types are not allowed for the type parameters.
HashMap<String , Integer> map8 = new HashMap<>();
- When data is added, HashMap approximately doubles its storage capacity.
- Therefore, if you know the initial number of data items to store, it's good practice to specify the initial capacity.
void clear(); #
- Clears all existing elements within the HashMap. It has no return value.
boolean isEmpty() #
- Checks if the HashMap contains any elements. Returns
trueif empty,falseotherwise.
boolean containsKey(Object Key) #
- Determines if the given
Keyexists in the current HashMap and returns a boolean value. (trueif present,falseif not).
boolean containsValue(Object value) #
- Determines if a
Keyassociated with the givenValueexists in the current HashMap and returns a boolean value.
Set<Map.Entry<K,V>> entrySet(); #
- Returns all elements of the HashMap as a
Set, bundled in "key=value" form.
Set KeySet() #
- Returns all keys of the HashMap as a
Set, bundled in key form.
Collection values() #
- Returns all values of the HashMap, bundled together.
V get #
- Returns the
valuemapped to the givenkey. - If the
keyis not present in the HashMap, it returnsnull.
V put(K key, V value) #
- Adds the given
key=valuepair to the HashMap. - If the
Keyalready exists in the HashMap, thevaluefrom the laterputoperation will be stored.
V remove(Object key) #
- If the given
keyexists in the HashMap, it removes thatkey=valuepair and returns thevalue. - If the given
keyis not in the HashMap, it returnsnull.
V replace(key, value) #
- Replaces an existing
key=old_valuein the HashMap with a newkey=value. - If the
replaceoperation is successful, it returns theold_valuethat existed previously; if thekeydoes not exist andreplacefails, it returnsnull.
void forEach #
- You can access each
key=valuepair of the HashMap usingforEach. - Lambda expressions can also be used, allowing for simpler code compared to iteration via an
Iterator. Sets created throughkeySet(),entrySet(), orvalues()can also be accessed with aforEachloop.