Build a simple PhoneBook program.

PhoneBook.java 2.0KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /**
  2. * Created by leon on 1/23/18.
  3. */
  4. import java.util.*;
  5. public class PhoneBook {
  6. private TreeMap<String, ArrayList<String>> book = new TreeMap<String, ArrayList<String>>();
  7. public ArrayList<String> add(String name, String phoneNumber) {
  8. ArrayList<String> converted = new ArrayList<String>();
  9. if (book.containsKey(name)) converted = book.get(name);
  10. converted.add(phoneNumber);
  11. add(name, converted);
  12. return book.get(name);
  13. }
  14. public ArrayList<String> add(String name, ArrayList<String> phoneNumbers) {
  15. book.put(name, phoneNumbers);
  16. return book.get(name);
  17. }
  18. public TreeMap<String, ArrayList<String>> remove(String name) {
  19. book.remove(name);
  20. return book;
  21. }
  22. public ArrayList<String> remove(String name, String number) {
  23. ArrayList<String> numbers = book.get(name);
  24. numbers.remove(numbers.indexOf(number));
  25. book.put(name, numbers);
  26. return book.get(name);
  27. }
  28. public ArrayList<String> lookup(String name) {
  29. return book.get(name);
  30. }
  31. public String reverseLookup(String phoneNumber) {
  32. String result = "none";
  33. for(Map.Entry<String, ArrayList<String>> entry : book.entrySet()) {
  34. ArrayList<String> numbers = entry.getValue();
  35. for (String number : numbers) {
  36. if (number.equals(phoneNumber)) result = entry.getKey();
  37. }
  38. }
  39. return result;
  40. }
  41. public String display() {
  42. StringBuilder result = new StringBuilder();
  43. for(Map.Entry<String, ArrayList<String>> entry : book.entrySet()) {
  44. result.append(entry.getKey() + " ");
  45. ArrayList<String> numbers = entry.getValue();
  46. for (String number : numbers) {
  47. result.append(number + " ");
  48. }
  49. result.append("\n");
  50. }
  51. return result.toString();
  52. }
  53. public static void main(String[] args) {
  54. PhoneBook phoneBook = new PhoneBook();
  55. };
  56. }