Creating an Application Using Java HashMap

Welcome! Today, we will explore creating a simple address book application using Java's HashMap. This task will help you understand how to manipulate a HashMap in Java, focusing on adding, retrieving, and deleting entries. By the end of this lesson, you'll have a solid grasp of these fundamental operations.

Introducing Methods to Implement

In this task, we will implement three methods to manage our address book:

  • addContact(String phoneNumber, String name): Adds a new contact. Returns false if the contact already exists; otherwise, it adds the contact and returns true. For this task, let's assume names do not change, so it's not allowed to overwrite an existing contact's name.
  • getContact(String phoneNumber): Retrieves the name for a given phoneNumber. Returns null if the contact does not exist.
  • deleteContact(String phoneNumber): Deletes a contact with the given phoneNumber. Returns true if the contact exists and is deleted, false otherwise.

Let's break down each method in detail in the following sections.

Step 1: Implementing addContact

This method adds a new contact to the address book with the given phoneNumber and name. If the contact already exists, it returns false. Otherwise, it adds the contact and returns true.

Question: Why do you think we need to check if the contact already exists?

Answer: To avoid duplicating existing entries. Also, if a contact with the same phone number already exists, we shouldn't allow overwriting its name in this method, as it's only for creation.

Here is the method implementation:

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

class AddressBook {
    private HashMap<String, String> contacts;

    public AddressBook() {
        contacts = new HashMap<>();
    }

    public boolean addContact(String phoneNumber, String name) {
        if (contacts.containsKey(phoneNumber)) {
            return false;
        }
        contacts.put(phoneNumber, name);
        return true;
    }

    public Map<String, String> getAllContacts() {
        return contacts;
    }
}

public class Solution {
    public static void main(String[] args) {
        AddressBook addressBook = new AddressBook();
        System.out.println(addressBook.addContact("123-456-7890", "Alice")); // True
        System.out.println(addressBook.addContact("123-456-7890", "Bob")); // False
        for (Map.Entry<String, String> contact : addressBook.getAllContacts().entrySet()) {
            System.out.println(contact.getKey() + ": " + contact.getValue()); // 123-456-7890: Alice
        }
    }
}

In this method:

  • We verify if the contact already exists using if (contacts.containsKey(phoneNumber)).
  • If it exists, we return false.
  • If it doesn't exist, we add it to our HashMap using contacts.put(phoneNumber, name); and return true.
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal