123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081 |
- import java.util.*;
-
- /**
- * Created by leon on 1/23/18.
- */
- public class PhoneBook {
- Map<String, List<String>> phoneBook = new TreeMap<String, List<String>>();
-
- 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<String> 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<String> listToUpdate = new ArrayList<>(phoneBook.get(name));
- Iterator<String> 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<String, List<String>> 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<String, List<String>> e : phoneBook.entrySet()){
- String printName = e.getKey();
- List<String> printNumber = e.getValue();
- System.out.printf(" %-20s %-12s\n", printName, printNumber);
- }
- System.out.printf("-----End of the phone book-----\n");
- }
- }
|