Build a simple PhoneBook program.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import java.util.*;
  2. /**
  3. * Created by leon on 1/23/18.
  4. */
  5. public class PhoneBook {
  6. String name;
  7. String phoneNumber;
  8. TreeMap<String, ArrayList<String>> phoneBook = new TreeMap<>();
  9. public PhoneBook(TreeMap<String, ArrayList<String>> phoneBook) {
  10. this.phoneBook = phoneBook;
  11. }
  12. public PhoneBook(){}
  13. public void add(String name, String phoneNumber){
  14. if (!phoneBook.containsKey(name)) {
  15. ArrayList<String> list = new ArrayList<>();
  16. list.add(phoneNumber);
  17. phoneBook.put(name, list);
  18. } else {
  19. ArrayList<String> temp = phoneBook.get(name);
  20. temp.add(phoneNumber);
  21. phoneBook.replace(name, phoneBook.get(name), temp);//key,old,new
  22. }
  23. }
  24. public void remove(String name, String phoneNumber){
  25. ArrayList<String> list = phoneBook.get(name);
  26. if(list.size() == 1) {
  27. phoneBook.remove(name);
  28. } else {
  29. ArrayList<String> temp = phoneBook.get(name);
  30. temp.remove(phoneNumber);
  31. phoneBook.replace(name,list,temp);
  32. }
  33. }
  34. public void removeRecord(String name) {
  35. phoneBook.remove(name);
  36. }
  37. public ArrayList<String> lookup(String name){
  38. return phoneBook.get(name);
  39. }
  40. public String reverseLookup(String phoneNumber) {
  41. // for each entry in phonebook
  42. for (Map.Entry<String, ArrayList<String>> entry : phoneBook.entrySet()) {
  43. // gets name
  44. String name = entry.getKey();
  45. // gets list of numbers
  46. ArrayList<String> list = entry.getValue();
  47. // if number equals the number we are looking for, return name
  48. for (String number: list) {
  49. if (number.equals(phoneNumber)) {
  50. return name;
  51. }
  52. }
  53. }
  54. return "Not found";
  55. }
  56. public String display() {
  57. // build a string to display
  58. StringBuilder sb = new StringBuilder();
  59. for (Map.Entry<String, ArrayList<String>> entry : phoneBook.entrySet()){
  60. String name = entry.getKey();
  61. ArrayList<String> numbers = entry.getValue();
  62. sb.append(name).append(" ");
  63. // for each number in element, append to name
  64. for (int i = 0; i < numbers.size(); i++) {
  65. sb.append(numbers.get(i));
  66. // append a space if i is not the last number in list
  67. if (i != numbers.size()-1) {
  68. sb.append(" ");
  69. }
  70. }
  71. sb.append("\n");
  72. }
  73. return sb.toString();
  74. }
  75. }