Tech With Tim Logo
Go back

Maps & HashMaps

Maps & HashMaps

If you have ever programmed before you may have heard of something called a dictionary. A map and a dictionary are precisely the same thing. Note that a HashMap is simply an implementation of a map (there are others as well).

A map can be defined simply as a key value pair. They work in a similar way to an array in the sense that a certain object/value can point to another. In the case of an array an int known as an index points to a certain element in the array. For maps any object can point to another. We call the object that we use to access another the key and the object it points to a value. We use keys to access values and our keys can be anything that we want.

It is important to note that our like sets our map has no order. This also means that the following operations are instant: add, remove or find.

To create a map we do the following.

import java.util.HashMap;
import java.util.Map;

Map m = new HashMap();
// Note that we do not need to define the type that we store in a map

Adding Key-Value Pairs

As mentioned above the elements in our map are known as key-value pairs. To create a new key-value pair we use .put()

import java.util.HashMap;
import java.util.Map;

Map m = new HashMap();
m.put("key1", 56);
//Now our map has one key value pair, the string "key1" points to the value 56

If we attempt to add a key that already exists we will override that key with the new value.

import java.util.HashMap;
import java.util.Map;

Map m = new HashMap();
m.put("key1", 56);
m.put("h", 98);
m.put("h", 1000)


System.out.println(m); // {"key1":56, "h":1000}

Map Methods

When we want to access a value in our map we must use the key. We can use .get(key) to retrieve a value from our map.

import java.util.HashMap;
import java.util.Map;

Map m = new HashMap();
m.put("key1", 56);

int x = m.get("key1");

System.out.println(x); // Prints 56

To check if a key exists in a map we can use .containsKey(). Same goes for a value .containsValue().

import java.util.HashMap;
import java.util.Map;

Map m = new HashMap();
m.put("key1", 56);
m.put("h", 98);
m.put("h", 1000)


System.out.println(m.containsKey("h")); // Prints true
System.out.println(m.containsValue("h")); // Prints false
System.out.println(m.containsKey(1000)); // Prints false
System.out.println(m.containsValue(1000)); // Prints true

Finally we can use .clear() to clear a map and .isEmpty() to check if a map is empty.

import java.util.HashMap;
import java.util.Map;

Map m = new HashMap();
m.put("key1", 56);
m.put("h", 98);

m.clear();
boolean empty = m.isEmpty();

System.out.println(empty); // Prints true

Different Kind of Maps

Like lists and sets Java has different kinds of maps. They are the following:

  • LinkedHashMap
  • TreeMap To find out more about different kinds of maps click here.
Design & Development by Ibezio Logo