Simple Phonebook

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import java.util.*;
  2. /**
  3. * Created by leon on 1/23/18.
  4. */
  5. public class PhoneBook {
  6. Map<String, List<String>> phoneBook = new TreeMap<String, List<String>>();
  7. public void addEntry(String name, String... phoneNumbers){
  8. phoneBook.put(name, Arrays.asList(phoneNumbers));
  9. }
  10. public void removeEntry(String name){
  11. phoneBook.remove(name);
  12. }
  13. public void addNumberToEntry(String name, String... phoneNumbers){
  14. List<String> listToUpdate = new ArrayList<>(phoneBook.get(name));
  15. for (String aNumber : phoneNumbers){
  16. listToUpdate.add(aNumber);
  17. }
  18. String[] updatedNumbers = listToUpdate.toArray(new String[listToUpdate.size()]);
  19. addEntry(name, updatedNumbers);
  20. }
  21. public void removeNumberFromEntry(String name, String... phoneNumbers){
  22. List<String> listToUpdate = new ArrayList<>(phoneBook.get(name));
  23. Iterator<String> i = listToUpdate.iterator();
  24. while(i.hasNext()){
  25. String aNumberInList = i.next();
  26. for (String aNumberToDelete : phoneNumbers){
  27. if (aNumberInList.equals(aNumberToDelete)){
  28. i.remove();
  29. }
  30. }
  31. }
  32. String[] updatedNumbers = listToUpdate.toArray(new String[listToUpdate.size()]);
  33. addEntry(name, updatedNumbers);
  34. }
  35. public String lookup(String name){
  36. if(phoneBook.get(name)==null){
  37. return null;
  38. }
  39. StringBuilder numbers = new StringBuilder();
  40. int counter = 0;
  41. for (String aNumber : phoneBook.get(name)){
  42. numbers.append(aNumber);
  43. counter++;
  44. if(counter != phoneBook.get(name).size()){
  45. numbers.append(", ");
  46. }
  47. }
  48. return numbers.toString();
  49. }
  50. public String reverseLookup(String... phoneNumbers){
  51. for(Map.Entry<String, List<String>> e : phoneBook.entrySet()){
  52. String name = e.getKey();
  53. for(String aNumberInList : phoneBook.get(name)){
  54. for (String aNumberToLookup : phoneNumbers){
  55. if(aNumberInList.equals(aNumberToLookup)){
  56. return e.getKey();
  57. }
  58. }
  59. }
  60. }
  61. return null;
  62. }
  63. public void display(){
  64. System.out.printf("%-20s%-12s\n", "Name", "Phone Number(s)");
  65. for(Map.Entry<String, List<String>> e : phoneBook.entrySet()){
  66. String printName = e.getKey();
  67. List<String> printNumber = e.getValue();
  68. System.out.printf(" %-20s %-12s\n", printName, printNumber);
  69. }
  70. System.out.printf("-----End of the phone book-----\n");
  71. }
  72. }