import java.util.TreeMap; import java.util.Set; import java.util.ArrayList; /** * Created by leon on 1/23/18. * Updated by allison on 5/30/18 */ public class PhoneBook { TreeMap> myFriendsDigits; public PhoneBook() { myFriendsDigits = new TreeMap>(); } public void add(String name, String phoneNumber) { if (lookup(name).equals("Not Found")){ ArrayList soManyDigits = new ArrayList(); soManyDigits.add(phoneNumber); myFriendsDigits.put(name, soManyDigits); } else { ArrayList soManyDigits = myFriendsDigits.get(name); soManyDigits.add(phoneNumber); } } public void add(String name, ArrayList phoneNumbers) { myFriendsDigits.put(name, phoneNumbers); } public void remove(String name) { myFriendsDigits.remove(name); } public void remove(String name, int phoneNumberIndex) { ArrayList phoneNumbers = myFriendsDigits.get(name); phoneNumbers.remove(phoneNumberIndex); } public String lookup(String name) { ArrayList phoneNumbers = myFriendsDigits.get(name); if (phoneNumbers != null) { return getPhoneNumberString(phoneNumbers); } else { return "Not Found"; } } public String reverseLookup(String phoneNumber) { Set names = myFriendsDigits.keySet(); for (String name : names) { if (searchPhoneNumberList(myFriendsDigits.get(name), phoneNumber)){ return name; } } return "Not Found"; } public void display() { Set names = myFriendsDigits.keySet(); for (String name : names){ System.out.println("Name: " + name + ": " + myFriendsDigits.get(name)); } } private boolean searchPhoneNumberList(ArrayList phoneNumbers, String theMagicNumber) { boolean found = false; for (int i = 0; i < phoneNumbers.size(); i++) { if (phoneNumbers.get(i).equals(theMagicNumber)) { found = true; break; } } return found; } private String getPhoneNumberString(ArrayList phoneNumbers) { StringBuilder formattedNumbers = new StringBuilder(); for (int i = 0; i < phoneNumbers.size(); i++) { if (i == phoneNumbers.size() - 1) { formattedNumbers.append(phoneNumbers.get(i)); } else { formattedNumbers.append(phoneNumbers.get(i) + ", "); } } return formattedNumbers.toString(); } }