import java.util.*; /** * Created by leon on 1/23/18. */ public class PhoneBook { String name; String phoneNumber; TreeMap> phoneBook = new TreeMap<>(); public PhoneBook(TreeMap> phoneBook) { this.phoneBook = phoneBook; } public PhoneBook(){} public void add(String name, String phoneNumber){ if (!phoneBook.containsKey(name)) { ArrayList list = new ArrayList<>(); list.add(phoneNumber); phoneBook.put(name, list); } else { ArrayList temp = phoneBook.get(name); temp.add(phoneNumber); phoneBook.replace(name, phoneBook.get(name), temp);//key,old,new } } public void remove(String name, String phoneNumber){ ArrayList list = phoneBook.get(name); if(list.size() == 1) { phoneBook.remove(name); } else { ArrayList temp = phoneBook.get(name); temp.remove(phoneNumber); phoneBook.replace(name,list,temp); } } public void removeRecord(String name) { phoneBook.remove(name); } public ArrayList lookup(String name){ return phoneBook.get(name); } public String reverseLookup(String phoneNumber) { // for each entry in phonebook for (Map.Entry> entry : phoneBook.entrySet()) { // gets name String name = entry.getKey(); // gets list of numbers ArrayList list = entry.getValue(); // if number equals the number we are looking for, return name for (String number: list) { if (number.equals(phoneNumber)) { return name; } } } return "Not found"; } public String display() { // build a string to display StringBuilder sb = new StringBuilder(); for (Map.Entry> entry : phoneBook.entrySet()){ String name = entry.getKey(); ArrayList numbers = entry.getValue(); sb.append(name).append(" "); // for each number in element, append to name for (int i = 0; i < numbers.size(); i++) { sb.append(numbers.get(i)); // append a space if i is not the last number in list if (i != numbers.size()-1) { sb.append(" "); } } sb.append("\n"); } return sb.toString(); } }