HashMap


Collapse Content

Arrays and ArrayLists in Java store data in order by index. This is useful in many circumstances, but sometimes you don't care about the order and just want to find things quickly. That's where the HashMap comes in.

The HashMap is a data structure which maps unique keys to specific values. HashMaps perform the lookup by "hashing" the key, i.e. performing some math operations to it that let it find the value. This allows "instant" lookup time to find any value in the HashMap.

Scenario

Lisa is a website administrator and wants a convenient way to store the username and password of her clients. Each client must choose a unique user name and sets their own password, therefore Lisa needs a data structure that associates a unique username with its respective password. HashMaps don't allow for duplicates and have fast-lookup time, so they would make a good choice.

Construction

The following will construct a HashMap with default size.

HashMap map = new HashMap();

Usually, you will want to specify the data types that the HashMap holds. For example, this will create a HashMap that stores Integer keys and String values:

  HashMap<Integer, String> numString = new HashMap<Integer, String>();

The HashMap constructor can also take in a Map and generate a HashMap with the mapping of that Map. Consider a Map called existingMap, it could be copied using the following code:

HashMap map = new HashMap(existingMap);

See here for more constructor details.

Methods

Let's start by putting a couple usernames and passwords into our HashMap.

map.put("username", "password");
map.put("jimmy", "123def");

numString.put(17, "hello");

Now let's check that our information was entered correctly. Printing a HashMap simply calls the toString method of the AbstractMap class.

System.out.println(map);

The output simply prints each pair of usernames and passwords separated by commas.

{username=password, jimmy=123def}

Removal

If Lisa were to encounter a situation where a client withdrew from her website she would need to remove both the username and password. The HashMap class provides a simple way of purging both simultaneously.

map.remove("username");
System.out.println(map);

This prints:

{jimmy=123def}

Since HashMap uses the usernames to index the passwords only the username itself is required for removal.

It is also possible to clear out the HashMap entirely using the clear method.

numString.clear();

Retrieval

Now assume that a client lost their password and need to retrieve it. The HashMap class also has an answer for this situation. In order to get a value within a HashMap use the following code:

String password = map.get("jimmy");
System.out.println(password);

Here the get method simply requires the key in order to retrieve the value which in our case are usernames and passwords. The printed result is the password associated with "user"

123def

Before adding a user to a HashMap, we want to check that no other user has the same username. HashMap can easily do this with the containsKey method:

String newUserName = "jimmy";
if(map.containsKey(newUserName))
        System.out.println("That username is being used");

HashMap also has a containsValue method which operates in the same fashion, though isn't as fast.

HashMap copying

There are two main ways to copy a HashMap:

  • The entrySet method returns a Set which contains the mappings of the HashMap.
  • The putAll method copies the Map which is passed in and overwrites the HashMap that is calling the method. It is important to note when using this method that it will delete any contents of the original Map.

This code:

Set set = map.entrySet();
System.out.println(set);

...will print:

[jimmy=123def]

While the following code:

HashMap newMap = new HashMap();
newMap.putAll(map);
System.out.println(newMap);

....will print:

{jimmy=123def}
Notice that the only difference between the two outputs is that the first is bound by [] while the other is bound by {}. This is because the first output is printing using the toString method of the Set class while the second uses the toString method of the AbstractMap class.

HashMap Extra Info

Additional methods exist in the HashMap class which provide useful information like whether the map is empty and how many key/value pairs are present:

  • The size method simply returns the number of key/value pairs.
  • The isEmpty simply returns true or false based on whether or not the HashMap is empty.

    int size = map.size();
    boolean empty = map.isEmpty();
    

Converting HashMap to Collection

To convert your HashMap into a Collection simply use the values method.

Collection coll = map.values();

Challenge

The code below demonstrates many of HashMap's methods (as shown above), but it's missing certain parts. Look over the code and add new code wherever it says TODO

Please sign in or sign up to submit answers.

Alternatively, you can try out Learneroo before signing up.

Comments

  • HI I ran this in eclipse and am getting the same output as here...
    HashMap map;
    map = new HashMap();

        map.put("user", "pass");
    
    cont...
  • It looks like it could print the items inside the hashmap in a different order (this is because HashMaps do not preserve the order of the elements). I simplified the problem so the correct solution

    cont...
All Node Comments
Contact Us
Sign in or email us at [email protected]