Custom Object as a Key in HashMap

Introduction

In this Java HashMap example I am going to tell you how to use custom object as a key in HashMap. In custom object as a key in HashMap example, I will show you how to work with user defined objects as keys in Map. To use user defined objects as keys in Map you need to tell Java how to compare user defined objects by overriding the hashCode() and equals() methods.

Most of the time you generally use Java API provided classes, for example, mostly String objects as keys for HashMap. So in situations, where you need to use custom object as a key in HashMap then you can use this example.

Prerequisites

Java at least 8

Object key Class

Create below Book class that overrides equals() and hashCode() methods. This class will be used as a key in the HashMap. This class has two fields or attributes – title and author.

In the below example, two attributes – title and author – will be used together as a single key for the HashMap. You can have as many attributes as a key for the HashMap.

package com.roytuts.java.custom.object.key.hashmap;

public class Book {

	private String title;
	private String author;

	public Book(String title, String author) {
		this.title = title;
		this.author = author;
	}

	public String getTitle() {
		return title;
	}

	public String getAuthor() {
		return author;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((author == null) ? 0 : author.hashCode());
		result = prime * result + ((title == null) ? 0 : title.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Book other = (Book) obj;
		if (author == null) {
			if (other.author != null)
				return false;
		} else if (!author.equals(other.author))
			return false;
		if (title == null) {
			if (other.title != null)
				return false;
		} else if (!title.equals(other.title))
			return false;
		return true;
	}

	@Override
	public String toString() {
		return "Book [title=" + title + ", author=" + author + "]";
	}

}

Related Posts:

Main Class

Create below main class which will test the user defined objects as keys in HashMap. Here I have put few entries into the map object first. Then I iterate through the map object using Java 8’s forEach() loop.

Next I create an object of Book class which already exists in the map object and verify whether this book object exists or not in the map object.

package com.roytuts.java.custom.object.key.hashmap;

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

public class CustomObjectAsKeyInHashMapApp {

	public static void main(String[] args) {

		Map<Book, String> bookMap = new HashMap<>();

		bookMap.put(new Book("Java", "James Gosling"), "Java");
		bookMap.put(new Book("C++", "Bjourn Stroustup"), "C++");
		bookMap.put(new Book("C", "Denish Ritche"), "C");
		bookMap.put(new Book("Databse", "C J Date"), "Database");

		System.out.println();

		bookMap.forEach((k, v) -> System.out.println(k + " => " + v));

		System.out.println();

		Book key = new Book("Java", "James Gosling");

		System.out.println("Is key: " + key + " available? " + bookMap.containsKey(key));

	}

}

Testing the Code

Running the main class will give you the following output:

Book [title=C++, author=Bjourn Stroustup] => C++
Book [title=Java, author=James Gosling] => Java
Book [title=C, author=Denish Ritche] => C
Book [title=Databse, author=C J Date] => Database

Is key: Book [title=Java, author=James Gosling] available? true

Hope you got an idea how to use your own Java class as a key for the HashMap.

Source Code

Download

Leave a Comment