Home and Learn: Java Programming Course


What is a HashMap in Java

Sometimes in your programming life, you'll need to store key/value pairs. A HashMap is a way to do just that in java. Let's see how they work.

Suppose you decided to map chemical elements to the number of protons they have. You want to do something like this:

Hydrogen 1
Helium 2
Lithium 3
Beryllium 4
Boron 5
Carbon 6
Nitrogen 7
Oxygen 8

We have a string for the element name and an integer for the proton number. How do we store these key/value pairs in Java? Well, with the aid of a HashMap, of course.

To use a HashMap in java, you need to an import statement at the top of your code. HashMaps live in the utilities library. So add this to a new project:

import java.util.hashMap;

In between the curly brackets of your main method, add this line:

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

This sets up a new HashMap with the name elements. Notice what's at the start:

HashMap<String, Integer>

After declaring that you want to set up a HashMap, you need a pair of angle brackets (<>). In between these angle brackets, you tell Java what sort of values will go in your key/value pairs. In the line above, we want to the Key to be a String and the Value to be an Integer.

(In case you were wondering what the difference is between int and Integer, int is a primitive data type while Integer is a class.)

You don't have to have a String first and then an Integer. You can have whatever you need. For example:

HashMap<String, String>

HashMap<Integer, String>

There's a whole lot more Class types you can use:

Character
Float
Byte
Short
Long
Double
Boolean

OK, so we have a HashMap set up called elements. The next step is to add key/value pairs to the HashMap. You do this with the put method of HashMaps.

elements.put("Hydrogen", 1);

After your HashMap name, type a dot, and then the word put. In between the round brackets after put, type your key name, Hydrogen, in this case. It's in double quotes because we specified a string as our Key. After a comma, type your value. Because our value is an integer, we've just typed 1, without double quotes. The line ends with a semicolon. So, this "puts" "Hydrogen" and 1 into the HashMap, with Hydrogen being the key and 1 its value.

Now put these key/value pairs into your HashMap:

elements.put("Helium", 2);
elements.put("Lithium", 3);
elements.put("Beryllium", 4);
elements.put("Boron", 5);
elements.put("Carbon", 6);
elements.put("Nitrogen", 7);
elements.put("Oxygen", 8);

So you can see something happening, add this to print the HashMap out:

System.out.println(elements);

Here's the code you should have so far:

import java.util.HashMap;

public class HashMapTutorial {

	public static void main(String[] args) {
	
		HashMap elements = new HashMap();
			
		elements.put("Hydrogen", 1);
		elements.put("Helium", 2);
		elements.put("Lithium", 3);
		elements.put("Beryllium", 4);
		elements.put("Boron", 5);
		elements.put("Carbon", 6);
		elements.put("Nitrogen", 7);
		elements.put("Oxygen", 8);
	
		System.out.println(elements);
	}
}

Run the code and you should see this appear in your console window:

{Boron=5, Oxygen=8, Hydrogen=1, Beryllium=4, Lithium=3, Helium=2, Nitrogen=7, Carbon=6}

As you can see, there's no order to the results, neither alphabetical nor numerical. That's because Java use some internal hash function to do the storing. HashMaps are not really meant to be read out in order. It's just a storage method for keys and their values. You can sort a Hashmap, and we'll do that soon. But it's a bit messy!

 

HashMap Operations

To see how many items are in your HashMap, use the size method:

elements.size();

System.out.println("Hashmap Size: " + elements.size());

You can easily delete an entry in your HashMap with the remove method:

elements.remove("Carbon");

To replace an entry, use this:

elements.replace(key_name, key_value_to_replace);

So, if we wanted to replace the value for Carbon, we'd do this:

elements.replace("Carbon", 14);

If you want to clear the entire HashMap, use the clear method:

elements.clear();

There's also a containsKey method you can use:

if (elements.containsKey("Carbon")) {

System.out.println("Yay, Carbon!");

}

And there's a containsValue:

if (elements.containsValue(6)) {

System.out.println("6 is covered");

}

 

Reading Keys and Values from a HashMap

To read out the key names, you can use a Java for each loop. Add this:

for (String atomName : elements.keySet()) {

System.out.println(atomName);

}

We're setting up a string called atomName. Each key name will then be place in this atomName String variable. Notice the use of keySet() on the end of elements. This is a method of HashMaps. As its name suggests, it's used to get the keys.

Run your code and you should see this appear in the output window:

Boron
Oxygen
Hydrogen
Beryllium
Lithium
Helium
Nitrogen
Carbon

You can get just the values for the keys, if you want. Add this foreach loop:

for (Integer protonNumber : elements.values()) {

System.out.println(protonNumber);

}

It's more or less the same as the previous one. Except, this time we use the values() method after the HashMap name (elements).

Run the code and you'll see the Integers associated with the key names printed out:

5
8
1
4
3
2
7
6

If you want to print out both the key names and their values, here's the code:

for (String atoms : elements.keySet()) {

System.out.println("Element " + atoms + " has " + elements.get(atoms) + " protons");

}

The method to notice this time is this;

elements.get(atoms)

We use get to get the value from a key name. (The key names are stored in the atoms variable.)

If you were asked, How many protons does Carbon have?, you could have just done this:

System.out.println(elements.get("Carbon"));

 

Get aKeyname from a Value

Getting the key name from a value is a little bit trickier. Well, a lot trickier!

Suppose we're asked, Print out which element has 5 protons. How do we solve this? This code will give us a solution:

import java.util.Map;


int protonNumber = 5;

for(Map.Entry atomMap: elements.entrySet()) {

	if (atomMap.getValue() == protonNumber){
	
		System.out.println("The element with " + protonNumber + " protons is " + atomMap.getKey());
		
	}
}

Put the import at the top of your code and try it out. You should see this print out:

The element with 5 protons is Boron

But the code itself uses something called a Map. In Java a Map is an interface. The Map interface has lots of classes derived from it, one of which is the HashMap.

We need the Map because we need access to these two methods:

getValue()
getKey()

In our for each loop, we're setting up a map variable called atomMap. We're then going through each key/value pair with the help of a method called entrySet().

Inside the loop, we have an if statement.

if (atomMap.getValue() == protonNumber){
}

We want to know when the protonNumber is equal to the value part of the atomMap. If it is, we print something out:

System.out.println("The element with " + protonNumber + " protons is " + atomMap.getKey());


OK, that wasn't easy. Even harder is when we try to sort the HashMap on the values.

 

Sorting HashMaps

Bear in mind that you don't really need to sort HashMaps. If you find yourself needing to, you're probably using the wrong data structure. An ArrayList or a simple list might suit you better. Simply because these will have sort methods built in, whereas HashMaps don't. With that said, let's see how to sort a HashMap.

 

HashMap Key Sort

This one is fairly simple. But you need to use another kind of map called a TreeMap. A TreeMap will automatically sort your HashMap based on the key name. First, add these two import statements to the top of you code:

import java.util.Map;
import java.util.TreeMap;

Now add this line:

Map<String, Integer> sortedElementsByKey = new TreeMap<>(elements);

We've set up a Map variable called sortedElementsByKey. This is a Map with a String and an Integer between angle brackets. These match the types from our HashMap. After an equal sign, we create a new TreeMap, passing it the name of our HashMap:

new TreeMap<>(elements)

Notice the empty angle brackets after TreeMap.

Print it with this:

System.out.println(sortedElementsByKey);

You should see this appear in your console window:

{Beryllium=4, Boron=5, Carbon=6, Helium=2, Hydrogen=1, Lithium=3, Nitrogen=7, Oxygen=8}

It's an alphabetically sorted HashMap.

Of course, the periodic table is not sorted on its element names but on the proton number. So, we need a way to sort on the values rather than the key names. This is where it gets tricky!

 

HashMap Value Sort

For this to work, we need three more import statements at the top of the code. Add these:

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;

The idea is that you loop round your HashMap and add the keys and their values to an ArrayList. After that, you sort the list. Once the list is sorted, you loop through the list and put the keys and values into a LinkMap. Here's some code to try out:

LinkedHashMap linkedMapElements = new LinkedHashMap<>();
ArrayList arryListElements = new ArrayList<>();
        
//ADD KEYS/VALUES TO LIST
for (Map.Entry val : elements.entrySet()) {

	arryListElements.add(val.getValue());

}

//SORT THE LIST
Collections.sort(arryListElements);
        
//PLACE KEYS AND VALUES INTO THE LinkMap
for (int tempVal : arryListElements) {
		
	for (Map.Entry val : elements.entrySet()) {

		if (val.getValue().equals(tempVal)) {
			
			linkedMapElements.put(val.getKey(), tempVal);
		}
	}
}
        
System.out.println(linkedMapElements);

Run the code and the output will be this:

{Hydrogen=1, Helium=2, Lithium=3, Beryllium=4, Boron=5, Carbon=6, Nitrogen=7, Oxygen=8}

At last - a HashMap sorted on the values! Study the code and it will eventually make sense. One day!

Feel free to complete the entire table of elements. Then, when someone asks you how many protons does gold have, you'll be able to tell them with this one line of code:

elements.get("Gold");

 

The next lesson is another intermediate lesson and takes a closer look at how to generate random numbers in Java. If you want to skip this tougher lesson, you can move on the error handling.

<-- Java Enumeration | Java Random Numbers -->

Java Error Handling -->

Back to the Java Contents Page

 


Email us: enquiry at homeandlearn.co.uk