Build a simple PhoneBook program.

PhoneBook.java 1.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import java.util.*;
  2. /**
  3. * Created by leon on 1/23/18.
  4. */
  5. public class PhoneBook {
  6. private TreeMap<String, ArrayList<String>> phoneBook;
  7. public PhoneBook() {
  8. phoneBook = new TreeMap<String, ArrayList<String>>();
  9. }
  10. public void add(String name, String phoneNumber) {
  11. ArrayList<String> input = phoneBook.containsKey(name) ?
  12. phoneBook.get(name)
  13. :
  14. new ArrayList<String>();
  15. input.add(phoneNumber);
  16. phoneBook.put(name, input);
  17. }
  18. public void removeEntry(String name) {
  19. phoneBook.remove(name);
  20. }
  21. public String lookup(String name) {
  22. return phoneBook.get(name)
  23. .toString()
  24. .replaceAll("[\\[\\]]", "");
  25. }
  26. public String reverseLookup(String phoneNumber) {
  27. String output = "";
  28. Set<String> keys = phoneBook.keySet();
  29. for (String key : keys) {
  30. if (phoneBook.get(key).contains(phoneNumber)) {
  31. output = key;
  32. }
  33. }
  34. return output.equals("") ? "No associated name." : output;
  35. }
  36. public String display() {
  37. return phoneBook.toString().replaceAll("[{}=,]", "")
  38. .replaceAll("\\[", " - ")
  39. .replaceAll("\\]", "\n");
  40. }
  41. public TreeMap getPhoneBook() {
  42. return phoneBook;
  43. }
  44. }