One of my favorite of all the Collections classes of Java is the HashMap. Its easy to use and easy to understand. HashMap is actually a hash table implementation of the Map interface. The HashMap class is equivalent of HashTable only that the HashMap allows null values and keys. Moreover hashmap is unsynchronized compared to HashTable. Since this is a lot faster because it is not synchronized however it would not be thread safe.

In dealing with this class, always remember that the order of elements is changing over time. In other words the placement of element on this pool of objects is dispersed.

Now that we have described the HashMap let’s take a look on a simple example.

Basic Example of HashMap


import java.util.HashMap;

 * Basic HashMap example 

public class HashMapBasicExample {

	public static void main(String[] args) {
		// initialization of our map
		HashMap<String, String> student = new HashMap<>();
		// adding elements to our hashmap
		student.put("age", "32");
		student.put("birthday","May 12, 1982");
		// getting the contents of our hashmap


The above example will yield on the following result

Name:May 12, 1982


The above example is very simple though the following lessons has been learned:

  • How to instantiate a hashmap. Specifying the type of key value pair
  • Its also been shown how to add elements on the hashmap using the put method.
  • The get() method were used to access the corresponding value of the specified key argument.

Now that we have know the basics of dealing with HashMap, lets try a more concrete example

HashMap of Objects

This example deals with the use of hashmap in storing of objects. There are a lot of things that happen to this example but to give you an overview here’s what it have.

  • Create a Student class which takes a string on its constructor.
  • The constructor must able to parse the string into tokens and assign it using the setters and getters of the Student class.
  • On the main Class create a init() method that instantiate objects of Students by calling its constructors
  • The init method should be able to return a HashMap with id as the key in getting Student values.
  • Print all the id number on the hashmap and then the student age with respect to the id number.

With the above requirements, please try to create the implementation and compare below for my solution

Here is the Student Class


import java.util.StringTokenizer;

public class Student {

	public Student(String s) {
		 * Pattern is id|name|bday|age|course

		// initializer our tokenizer
		StringTokenizer st = new StringTokenizer(s, "|");
		// set the values


	public Student() {

	String name;

	public String getName() {
		return name;

	public void setName(String name) { = name;

	public String getAge() {
		return age;

	public void setAge(String age) {
		this.age = age;

	public String getBirthday() {
		return birthday;

	public void setBirthday(String birthday) {
		this.birthday = birthday;

	public String getCourse() {
		return course;

	public void setCourse(String course) {
		this.course = course;

	public String getGender() {
		return gender;

	public void setGender(String gender) {
		this.gender = gender;

	public String getStudentid() {
		return studentid;

	public void setStudentid(String studentid) {
		this.studentid = studentid;

	String age;
	String birthday;
	String course;
	String gender;
	String studentid;



And below is our Main Class


import java.util.HashMap;


 * Example of Advance use of hashmap

public class HashMapObjectExample {

	public static void main(String[] args) {

		HashMap<String, Student> map = new HashMap<String, Student>();
		map = init();
		// iterate to all the keys stored on our hashmap
		for (String s : map.keySet()) {
			// print the student id and age
			System.out.println("Student with id number:" + s + " is "
					+ map.get(s).getAge() + " years old");

	private static HashMap<String, Student> init() {
		// initialize our student objects
		Student s1 = new Student(
				"100212554|Gary Valenciano|January 10, 1993|21|BS Math");
		Student s2 = new Student(
				"101292574|Vic Castro|May 10, 1995|18|Mechaninal Engineering");
		Student s3 = new Student(
				"201212444|Joel Uy|February 17, 1994|20|BS Education");
		Student s4 = new Student(
				"172324448|Louise Valenciano|December 10, 1985|29|Medicine");

		// initialize of hashmap
		HashMap<String, Student> map = new HashMap<String, Student>();

		// assign each student id as key and the student objects as values on
		// our hashmap
		map.put(s1.getStudentid(), s1);
		map.put(s2.getStudentid(), s2);
		map.put(s3.getStudentid(), s3);
		map.put(s4.getStudentid(), s4);

		return map;



Sample Output:

Running the above java example will give the following console output:

HashMap of Objects

HashMap of Objects


There are a lot of things that can be learned from the above example. It looks very complicated, but it is very easy because we only applied the basics of Java. Let’s take a look below on the knowledge that we have used:

  • The example above has the following code snippet
    HashMap<String, Student> map = new HashMap<String, Student>();

Basically we just instantiate a hashmap that takes a String object as its keys and a Student as its values. This is basic of Generics. We have used Generics to avoid mistake in passing arguments to our HashMap. To make it short this HashMap wont accept Integer or any other Object type as its keys. Moreover the value will not accept any other object other than Student object or its subclass.

  • The use of the constructor to initialize the values of the student class. This is very simple idea, pass a string to the constructor and then use StringTokenizer to broken down the string argument into tokes.
  • Use of the setters and getters to set and access the attributes of Student.
  • We have also used one helpful method of the HashMap class which is the keySet(). This method returns a Set which corresponds to the keys on our HashMap. We then use these keys to get the values on our HashMap and eventually we now have access to all the attributes of Student object.

HashMap Method Usage Examples

The following are the detailed list of HasMap methods and descriptions. We have also provided links to examples of each method on the list.

Modifier and Type Method and Description
void clear()
Basically this method is to delete all key value pair mapping on the HashMap. After invoking this method, the HashMap will be empty thus calling the isEmpty() method will return true.
Object clone()
Returns a shallow copy of this HashMap instance: the keys and values themselves are not cloned.
V compute(K key, BiFunction<? super K,? super V,? extends V> remappingFunction)
Attempts to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping).
V computeIfAbsent(K key, Function<? super K,? extends V> mappingFunction)
If the specified key is not already associated with a value (or is mapped to null), attempts to compute its value using the given mapping function and enters it into this map unless null.
V computeIfPresent(K key, BiFunction<? super K,? super V,? extends V> remappingFunction)
If the value for the specified key is present and non-null, attempts to compute a new mapping given the key and its current mapped value.
boolean containsKey(Object key)
is used to check if the key that we have is available on the list of keys on our HashMap object. Generally we need to pass an object as method argument to the containsKey() method.
boolean containsValue(Object value)
this method is to check if the HashMap contains the Object value specified as method argument. This method returns true if one or more keys were found that contains the specified value, otherwise return false. This would be helpful on scenario wherein we have to check the existence of a specific name already only the map so as to avoid duplication.
Set<Map.Entry<K,V>> entrySet()
return a set which is a view of the HashMap object. Because this method is backed with Map class, any change on our HashMap will get instantly reflected on the Set and vice versa.
void forEach(BiConsumer<? super K,? super V> action)
Performs the given action for each entry in this map until all entries have been processed or the action throws an exception.
V get(Object key)
returns the value which corresponds to the key specified as method argument.
V getOrDefault(Object key, V defaultValue)
return a default value whenever the value was not found using the key specified on the HashMap.
boolean isEmpty()
returns true if the HashMap object contains zero key-value combinations. This method might be useful in situation wherein we have to test if the map is empty or not and do business logic depending on the result.
Set keySet()
get all the keys that the HashMap contains. This method can strategically be used to iterate to all the contents of the HashMap which means this is a good way to get the values.
V merge(K key, V value, BiFunction<? super V,? super V,? extends V> remappingFunction)
If the specified key is not already associated with a value or is associated with null, associates it with the given non-null value.
V put(K key, V value)
add key value pair to the HashMap object. Please take note of the Generics before using the put method.
void putAll(Map<? extends K,? extends V> m)
Copies all of the mappings from the specified map to this map.
V putIfAbsent(K key, V value)
Basically this method is being used to insert a new a new key-value mapping to the hashmap object if the respective id is not yet used. A value null will be returned if the key-value mapping is successfully added to the hashmap object while if the id is already present on the hashmap the value which is already existing will returned instead.
V remove(Object key)
remove/delete key value pair to the HashMap object with the key as the method input. As other methods of HashMap class, Generics should also be considered in using the remove() method.
boolean remove(Object key, Object value)
Removes the entry for the specified key only if it is currently mapped to the specified value.
V replace(K key, V value)
accepts a key and a value mapping which will replace the existing value of the key-value mapping by the value method argyment if the key is found on the HashMap otherwise the method will not do anything.
boolean replace(K key, V oldValue, V newValue)
this method will only replace the existing key-value mapping if the key and oldValue is found on the HashMap.
void replaceAll(BiFunction<? super K,? super V,? extends V> function)
Replaces each entry’s value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception.
int size()
Returns the number of key-value mappings in this map.
Collection values()
Returns a Collection view of the values contained in this map.