Java

How to use HashMap in Java

Before knowing how to use a hashMap in Java, the reader has to know what a hashmap is. Consider the following key/value pairs of fruits and their colors:

    Red Apple => red
    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

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:

import java.util.*;

class TheClass {

    public static void main(String[] args) {    

        HashMap hm = new HashMap();

    }  
}

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:

import java.util.*;

class TheClass {

    public static void main(String[] args) {    

        HashMap hm = new HashMap(20);

    }  
}

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:

import java.util.*;

class TheClass {

    public static void main(String[] args) {    

        HashMap hm = new HashMap(20,0.62f);

    }  
}

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:

import java.util.*;

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:

        String V = hm.putIfAbsent("Watermelon", "green");
        System.out.println(V);

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:

        int sz = hm.size();

isEmpty()
This method, returns true if the hashmap contains no key-value mappings, or false otherwise. Example:

        boolean bl = hm.isEmpty();
        System.out.println(bl);

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:

        String str = hm.get("Banana");
        System.out.println(str);

containsKey(Object key)
Returns true if there is a mapping for that particular key; false otherwise. Example:

        boolean bl = hm.containsKey("Banana");

containsValue(Object value)
Returns true if there is a mapping for that value; false otherwise. Example:

        boolean bl = hm.containsValue("green");

keySet()
This method returns all the keys of the key/value pairs. Example code:

        Set st = hm.keySet();
        for (String val : st)
            System.out.print(val + ", ");
        System.out.println();

Note that the return object is a set. If the above original hashmap is used, the output would be:

    lemon, Kivi, Fig, Grape, lime, Avocado, Red Apple, Banana,

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:

        Collection cl = hm.values();
        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:

    pale yellow, green, purple, purple, yellow-green, green, red, yellow,

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:

        Set<Map.Entry> stm = hm.entrySet();
        for (Map.Entry kv : stm)
            System.out.println(kv.getKey() + " => " +  kv.getValue());

If the above original hashmap is used, the output would be:

    lemon => pale yellow
    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:

        String V = hm.replace("Banana", "white");
        System.out.println(V);
        String str = hm.get("Banana");
        System.out.println(str);

The output is:

    yellow
    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:

        boolean bl = hm.replace("Grape", "purple", "brown");
        System.out.println(bl);

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:

        String V = hm.remove("Banana");
        System.out.println(V);

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:

        boolean bl = hm.remove("Avocado", "green");
        System.out.println(bl);

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

About the author

Chrysanthus Forcha

Discoverer of mathematics Integration from First Principles and related series. Master’s Degree in Technical Education, specializing in Electronics and Computer Software. BSc Electronics. I also have knowledge and experience at the Master’s level in Computing and Telecommunications. Out of 20,000 writers, I was the 37th best writer at devarticles.com. I have been working in these fields for more than 10 years.