Build a simple PhoneBook program.

PhoneBook.java 1.9KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. ArrayList<String> list;
  15. if (!phoneBook.containsKey(name)) {
  16. list = new ArrayList<>();
  17. phoneBook.put(name, list);
  18. }
  19. else
  20. {
  21. list = phoneBook.get(name);
  22. list.add(phoneNumber);
  23. phoneBook.replace(name, list);
  24. }
  25. }
  26. public void remove(String name){
  27. phoneBook.remove(name);
  28. }
  29. public String lookup(String name){
  30. ArrayList<String> numbers = phoneBook.get(name);
  31. StringBuilder sb = new StringBuilder();
  32. for (int i=0; i<numbers.size(); i++) {
  33. sb.append(numbers.get(i));
  34. if (i == numbers.size()-1) {
  35. break;
  36. } else {
  37. sb.append(", ");
  38. }
  39. }
  40. sb.append("");
  41. return sb.toString();
  42. }
  43. public String reverseLookup(String phoneNumber) {
  44. for (Map.Entry<String, ArrayList<String>> e : phoneBook.entrySet()) {
  45. String name = e.getKey();
  46. ArrayList<String> numbers = e.getValue();
  47. for (String s : numbers) {
  48. if (s == phoneNumber) {
  49. return name;
  50. }
  51. }
  52. }
  53. return "Name not found";
  54. }
  55. public String display() {
  56. StringBuilder sb = new StringBuilder();
  57. for (Map.Entry<String, ArrayList<String>> e : phoneBook.entrySet()){
  58. String name = e.getKey();
  59. ArrayList<String> numbers = e.getValue();
  60. sb.append(name).append(" ");
  61. for (int i=0; i<numbers.size(); i++) {
  62. sb.append(numbers.get(i));
  63. if (i == numbers.size()-1) {
  64. break;
  65. } else {
  66. sb.append(", ");
  67. }
  68. }
  69. sb.append("");
  70. }
  71. return sb.toString();
  72. }
  73. }