Banana => yellow
lemon => pale yellow
lime => yellow green
Kivi => green
Avocado => green
Grape => purple
Fig => purple
=> - - - - -
=> - - - - -
=> - - - - -
The column on the left has the keys, and the column on the right has the corresponding values. Note that the fruits, kivi, and avocado have the same color, green. Also, the fruits, grapes, and figs have the same color, purple. At the end of the list, three locations are waiting for their own colors. These locations have no corresponding fruits; in other words, these three locations have no corresponding keys.
All locations, whether filled or not, on the right, are called buckets. For each value, there is a key. The keys are unique. The values do not have to be unique. This is a many-to-one relationship.
What is stored in the table is the right column. That is, what is stored in the table are the values. Keys do not have to be stored. The key is sent as an argument to a function called a hash function to arrive at a value. The hash function produces the corresponding index that is associated with a particular value.
Any structure that suits all the above descriptions is called a hash. With the hashmap in Java, the keys are of one object type, and the values are of another object type. There can be one null key, and there can be more than one null value.
The size of a hashmap is the number of key/value pairs (entries). The capacity of a hashmap is the number of buckets, whether filled or not. The capacity should always be greater than the size.
With the above introduction, the reader can now learn how to use a hashmap in Java.
Article Content
- Construction
- Including Key/Value Pairs
- Size of HashMap
- Reading the HashMap
- Modifying the HashMap
- Conclusion
Construction
The hashMap is a class from which a hashMap object can be created. Creating an object from a class is constructing the object. There are 4 ways of constructing a hashMap in Java.
Load Factor
The load factor is the number of key/value pairs divided by the number of buckets.
HashMap()
This constructor method would create a hashmap of capacity 16 and of the load factor 0.75. This means the number of buckets will be 16 (and empty), and the default load factor is 0.75. After the creation of the hashmap, key/value pairs will be included. In this case, when the number of key/value pairs reaches 12, at 12/16 = 0.75, the hashMap will rehash automatically. This means that it will automatically increase the number of buckets to 32 (doubling). The following code shows how to create a hashmap object using this constructor:
The HashMap class is in java.util package. For this code, the keys would be strings, and the values would also be strings.
HashMap(int initialCapacity)
This allows the programmer to start with a different capacity but still with a load factor of 0.75. Illustration:
So, the hasmap object here starts with 20 empty buckets. Here the keys are integers. They differ from array indexes in the sense that the first index is not necessarily zero. Also, the indexes are not contiguous. For example, the first index maybe 20; the next one is 35, the one after 52, etc.
Note: with the hashmap, the ordering of the key/value pairs is not maintained. That is, if a set of key/value pairs is included in one order, on displaying the content, the order will be different, though all the included key/value pairs would still be there.
Key/value pairs for the hashMap are better referred to as mappings.
HashMap(int initialCapacity, float loadFactor)
Here, the load factor is quoted as well. The load factor is a float type and not an integer type. Here, a load factor different from 0.75 is quoted. There are advantages and disadvantages to having a load factor that differs from 0.75 – see later. Illustration:
Note the use of ‘f’ as the suffix for load factor.
HashMap(Map<? extends K,? extends V> m)
This constructor will create a hashmap from a map that already exists – see later.
Including Key/Value Pairs
put(K key, V value)
This method relates a particular value to a particular key. The key is actually hashed into an index that is directly associated with the value. However, it is the programmer or user that decides on the value and its key. The following example creates a hasmap, hm and includes all the key/value pairs and the empty buckets from above:
class TheClass {
public static void main(String[] args) {
HashMap hm = new HashMap(11);
hm.put("Red Apple", "red");
hm.put("Banana", "yellow");
hm.put("lemon", "pale yellow");
hm.put("lime", "yellow green");
hm.put("Kivi", "green");
hm.put("Avocado", "green");
hm.put("Grape", "purple");
hm.put("Fig", "purple");
}
}
The capacity is 11. The number of key/value pairs is 8. This means the size is 8. So, the effective load factor is 8/11 = 0.73f. The number of empty buckets is 11 – 8 = 3.
putIfAbsent(K key, V value)
This includes the key/value pair if the key does not already exist in the hashmap. In this case, the return value is null. If the key already exists, nothing changes, and the old value for the key is returned. If the following code is added to the bottom of the above code (in main()), then the output would be null:
Note: put(K key, V value) would displace the key/value pair for the key in question that is already there, effectively giving a new value for the key.
Size of HashMap
The size of the hashmap is the number of key/value pairs.
size()
The following statement will return the size of the hashMap:
isEmpty()
This method, returns true if the hashmap contains no key-value mappings, or false otherwise. Example:
An empty hashMap can have empty buckets.
Reading the HashMap
get(Object key)
Returns (copies out) the value corresponding to the key; or returns null if there is no corresponding value. Example:
containsKey(Object key)
Returns true if there is a mapping for that particular key; false otherwise. Example:
containsValue(Object value)
Returns true if there is a mapping for that value; false otherwise. Example:
keySet()
This method returns all the keys of the key/value pairs. Example code:
Note that the return object is a set. If the above original hashmap is used, the output would be:
Note that the order is not the order in which the keys were included.
values()
This method returns a collection of all the values in the hashmap. Example code:
for (String val : cl)
System.out.print(val + ", ");
System.out.println();
Note that the return object is a collection. If the above original hashmap is used, the output would be:
Note that the order is not the order in which the values were included.
entrySet()
This returns all the key/value pairs, but the programmer has to separate each key from its corresponding value. Example code:
If the above original hashmap is used, the output would be:
Kivi => green
Fig => purple
Grape => purple
lime => yellow green
Avocado => green
Red Apple => red
Banana => yellow
Note that the order is not the order in which the key/value pairs were included.
Modifying the HashMap
put(K key, V value)
The put() method is similar to the putIfAbsent() method in that if the key already exists, the old value is returned, and if the key does not already exist, null is returned. Do not forget that put() replaces the old value if the key already exists. If the key does not already exist, put() includes the new entry (key/value pair).
replace(K key, V value)
For a key that is already in place, this method is used to replace the value for the corresponding key. The hashmap is a many-to-one structure. An example code for the above hashmap is:
The output is:
white
The replace() method returns the old value. If the key does not exist, it returns null, and nothing is replaced.
replace(K key, V oldValue, V newValue)
This enables the replacement of a particular value that the programmer is aware of. It returns true if it succeeded and false if it did not. Example code for the above hashmap object is:
remove(Object key)
This removes the key/value pair mapped by the key. It returns the corresponding value removed. It returns null if the key was not present. Example code for the above hashmap is:
remove(Object key, Object value)
This enables removing an entry (key/value pair) for a particular value that the programmer is aware of. It returns true if it succeeded and false if it did not. Example code for the above hashmap object is:
Conclusion
An array can be considered as a mapping of indexes to values (of a particular type). A hashmap should be used when the mapping of one object type to another object type is needed. In this way, there are key/value pairs. A hash is a data structure where the number of values is limited, but the number of possible keys is more than the number of possible values. And so keys have to be hashed to arrive at the values. Java HashMap for its implicit hash function has been presented above. The programmer can write his own hashing (mapping) function. However, that is a topic for some other time.
Chrys
from Linux Hint https://ift.tt/3rtP0NQ
0 Comments