Start learning free

LESSON 132 OF 671 · DICTIONARIES - CHALLENGES

Add a Contact in Java: containsKey Before put

Practice Read the full explanation

You get a phone book phoneBook, a HashMap from names to phone numbers. You also get a name and a phone number.

Add name with its number to the phone book, and return the phone book.

Only add name when it isn't in the phone book yet. A name that is already there keeps its old number. The order of the entries doesn't matter.

 

Example 1:

Input: phoneBook = {"Ana": "555-0142", "Ben": "555-0199"}, name = "Cara", number = "555-0123"
Output: {"Ana": "555-0142", "Ben": "555-0199", "Cara": "555-0123"}
Explanation: "Cara" isn't in the phone book yet, so she is added.

Example 2:

Input: phoneBook = {"Ana": "555-0142", "Ben": "555-0199"}, name = "Ben", number = "555-0100"
Output: {"Ana": "555-0142", "Ben": "555-0199"}
Explanation: "Ben" is already in the phone book. He keeps his old number, "555-0199".

Example 3:

Input: phoneBook = {}, name = "Max", number = "555-0100"
Output: {"Max": "555-0100"}
Explanation: The phone book was empty. Now it has one contact.

 

Constraints:

  • phoneBook can be empty.
  • Names are single words made of English letters.
  • Every phone number has three digits, a dash and four digits, like "555-0142".
  • Two people can share a phone number.
STEP 1 OF 3
    Ctrl + Enter to check

    JAVA · DICTIONARIES - CHALLENGES

    Add Contact in Java, explained

    Problem overview

    The method addContact receives a phone book phoneBook, a HashMap from names to phone numbers, plus a name and a number. It adds the name with its number and returns the phone book, but only when the name is not in the book yet. A name that is already there keeps its old number. The phone book may be empty, and the order of entries does not matter.

    For a book with Ana and Ben and the new name Cara, Cara is added. For the name Ben with a new number, nothing changes, and Ben keeps 555-0199. For an empty book and Max, the book gets one contact.

    Approach

    The catch is what put does with an existing key: it replaces the old value. So calling put straight away would overwrite Ben's number, which the task forbids. The fix is to ask first. phoneBook.containsKey(name) is true when the name is already a key, so !phoneBook.containsKey(name) is true only for a new name. Only then do we put.

    Step by step

    1. Write the check if (!phoneBook.containsKey(name)) and close its braces. For a name already in the book, nothing should happen.
    2. Inside it, put the name with its number. On a new key, put adds the entry.
    3. After the if, return phoneBook: with the new contact, or as it was.

    The solution in Java

    class Solution {
        public HashMap<String, String> addContact(HashMap<String, String> phoneBook, String name, String number) {
            if (!phoneBook.containsKey(name)) {
                phoneBook.put(name, number);
            }
            return phoneBook;
        }
    }
    

    Details worth knowing:

    • The method changes the map it receives and returns that same map.
    • Both the keys (names) and the values (numbers) are Strings here.
    • Numbers are never checked for duplicates, because two people may share a number. Only the key matters.

    Edge cases and common mistakes

    • Calling put without the check. phoneBook.put("Ben", "555-0100") silently replaces Ben's number: the map then holds {Ben=555-0100} for that key.
    • Forgetting the !. Without it, the code only touches names that already exist, and new names are never added.
    • Checking the number instead of the name. The key is the name, so containsKey(number) asks the wrong question.
    • Empty book. containsKey on an empty map is false, so the contact is added.

    Why not always put?

    It might seem simpler to call put every time. The difference only shows for a name that is already there, and that is the case the task singles out: put replaces the number, and the task says the old one stays. The containsKey check is the whole difference between "add a contact" and "add or overwrite a contact".

    Testing

    Results, printed as key: value lines sorted by key, as the lesson's tests print them:

    • Ana 555-0142, Ben 555-0199, name Cara, number 555-0123 gives Ana: 555-0142, Ben: 555-0199, Cara: 555-0123.
    • The same book with name Ben and number 555-0100 gives Ana: 555-0142, Ben: 555-0199.
    • An empty book with Max and 555-0100 gives Max: 555-0100.
    Keep going with Java500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free