Stop 08 · Collections & GenericsProjects · 1/1

Contact Book with HashMap

Part of the Java Roadmap

In short

Time to put maps, records, comparators and file saving together in a tool you would actually use: a console contact book that finds anyone by name instantly and remembers everything between runs.

A console contact book that adds, searches, updates and deletes contacts stored in a HashMap, with sorted listing and file saving. It practises collections, generics and comparators.

The jaadu sits beside an old landline phone, flipping open a worn tabbed phone diary to exactly the right page with a triumphant grin.

Think of it like this

Your family's phone diary

Every Indian home once had a small phone diary by the landline, one page per letter. Looking someone up meant flipping to the right page, not reading every entry. A HashMap keyed by name is that diary, except it jumps to the right page in one step and never runs out of space.

Watch it happen

Life of one command

Read input
Normalise key
HashMap
Sort
Save CSV

1/5The user types: find Priya Sharma.

The big ideas

What you need to know

Map<String, Contact>

Key by a normalised name so lookups, updates and deletes are all average O(1).

A record for the data

record Contact(String name, String phone, String city) gives you equals, hashCode and toString for free.

Sorted listing

Copy values() into a List and sort with Comparator.comparing(Contact::city).thenComparing(Contact::name).

Persist to a file

Write one line per contact on exit and read them back on start, so nothing is lost between runs.

How it works

Build it in five steps

  1. 1

    Model

    Create the Contact record and a ContactBook class holding a HashMap.

  2. 2

    CRUD

    Add add, find, updatePhone and delete methods, each returning whether it worked.

  3. 3

    List

    Return contacts sorted by city and name using a Comparator chain.

  4. 4

    Menu

    Loop over a Scanner menu: add, find, update, delete, list, exit.

  5. 5

    Save and load

    Write contacts.csv with Files.write and load it with Files.readAllLines at start-up.

See it in code

Walk through the code

java
1import java.io.IOException;2import java.nio.file.*;3import java.util.*;4 5public class ContactBook {6    record Contact(String name, String phone, String city) {}7 8    private final Map<String, Contact> contacts = new HashMap<>();9 10    private static String key(String name) {11        return name.trim().toLowerCase();12    }13 14    public boolean add(Contact c) {15        return contacts.putIfAbsent(key(c.name()), c) == null;16    }17 18    public Optional<Contact> find(String name) {19        return Optional.ofNullable(contacts.get(key(name)));20    }21 22    public boolean updatePhone(String name, String phone) {23        Contact old = contacts.get(key(name));24        if (old == null) return false;25        contacts.put(key(name), new Contact(old.name(), phone, old.city()));26        return true;27    }28 29    public boolean delete(String name) {30        return contacts.remove(key(name)) != null;31    }32 33    public List<Contact> sorted() {34        List<Contact> list = new ArrayList<>(contacts.values());35        list.sort(Comparator.comparing(Contact::city).thenComparing(Contact::name));36        return list;37    }38 39    public void save(Path file) throws IOException {40        List<String> lines = new ArrayList<>();41        for (Contact c : sorted()) {42            lines.add(c.name() + "," + c.phone() + "," + c.city());43        }44        Files.write(file, lines);45    }46 47    public static void main(String[] args) throws IOException {48        ContactBook book = new ContactBook();49        book.add(new Contact("Priya Sharma", "98200 11223", "Mumbai"));50        book.add(new Contact("Rahul Verma", "99100 44556", "Delhi"));51        book.updatePhone("priya sharma", "98200 99887");52        book.find("Rahul Verma").ifPresent(System.out::println);53        book.sorted().forEach(System.out::println);54        book.save(Path.of("contacts.csv"));55    }56}

1/4Contacts are stored by a trimmed, lowercased name so "Priya Sharma" and "priya sharma " match.

The core of the contact book. Add a Scanner menu loop and a load method that reads contacts.csv to finish it.

Save yourself the pain

Common mistakes

Oops

Using the raw name as the key, so "Rahul" and "rahul" become two contacts.

Do this instead

Normalise keys with trim() and toLowerCase() everywhere you read or write the map.

Oops

Returning null from find() and forgetting to check it.

Do this instead

Return Optional<Contact> so the caller must handle the "not found" case.

Oops

Saving only when the user picks exit, so a crash loses everything.

Do this instead

Save after every change, or at least wrap the menu loop so save runs in a finally block.

Your mission

Finish and extend the contact book

~90 min

Quick check

Why does the contact book store keys as name.trim().toLowerCase()?

Go deeper

  1. 1Store contacts in a Map keyed by phone number to prevent duplicates.
  2. 2List contacts sorted by name using a Comparator.
  3. 3Add search by partial name and save data to a file between runs.

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge