import java.util.*; /** * Created by leon on 1/23/18. */ public class PhoneBook { Map> phoneBook = new TreeMap>(); public void addEntry(String name, String... phoneNumbers){ phoneBook.put(name, Arrays.asList(phoneNumbers)); } public void removeEntry(String name){ phoneBook.remove(name); } public void addNumberToEntry(String name, String... phoneNumbers){ List listToUpdate = new ArrayList<>(phoneBook.get(name)); for (String aNumber : phoneNumbers){ listToUpdate.add(aNumber); } String[] updatedNumbers = listToUpdate.toArray(new String[listToUpdate.size()]); addEntry(name, updatedNumbers); } public void removeNumberFromEntry(String name, String... phoneNumbers){ List listToUpdate = new ArrayList<>(phoneBook.get(name)); Iterator i = listToUpdate.iterator(); while(i.hasNext()){ String aNumberInList = i.next(); for (String aNumberToDelete : phoneNumbers){ if (aNumberInList.equals(aNumberToDelete)){ i.remove(); } } } String[] updatedNumbers = listToUpdate.toArray(new String[listToUpdate.size()]); addEntry(name, updatedNumbers); } public String lookup(String name){ if(phoneBook.get(name)==null){ return null; } StringBuilder numbers = new StringBuilder(); int counter = 0; for (String aNumber : phoneBook.get(name)){ numbers.append(aNumber); counter++; if(counter != phoneBook.get(name).size()){ numbers.append(", "); } } return numbers.toString(); } public String reverseLookup(String... phoneNumbers){ for(Map.Entry> e : phoneBook.entrySet()){ String name = e.getKey(); for(String aNumberInList : phoneBook.get(name)){ for (String aNumberToLookup : phoneNumbers){ if(aNumberInList.equals(aNumberToLookup)){ return e.getKey(); } } } } return null; } public void display(){ System.out.printf("%-20s%-12s\n", "Name", "Phone Number(s)"); for(Map.Entry> e : phoneBook.entrySet()){ String printName = e.getKey(); List printNumber = e.getValue(); System.out.printf(" %-20s %-12s\n", printName, printNumber); } System.out.printf("-----End of the phone book-----\n"); } }