Build a simple PhoneBook program.

PhoneBook.java 1.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import java.util.*;
  2. /**
  3. * Created by leon on 1/23/18.
  4. */
  5. public class PhoneBook {
  6. private Map<String, ArrayList<String>> phoneBook;
  7. public PhoneBook() {
  8. phoneBook = new TreeMap<String, ArrayList<String>>();
  9. }
  10. public ArrayList<String> add(String name, String number) {
  11. if (phoneBook.get(name) == null) {
  12. phoneBook.put(name, new ArrayList<String>());
  13. }
  14. phoneBook.get(name).add(number);
  15. return phoneBook.get(name);
  16. }
  17. public ArrayList<String> lookup(String name) {
  18. return phoneBook.get(name);
  19. }
  20. public String reverseLookup(String phoneNumber) {
  21. String name = "not found";
  22. for (Map.Entry<String, ArrayList<String>> entry : phoneBook.entrySet()) {
  23. for (String numbers : entry.getValue()) {
  24. if (numbers.equals(phoneNumber)) name = entry.getKey();
  25. }
  26. }
  27. return name;
  28. }
  29. public String display() {
  30. StringBuilder phoneNumbers = new StringBuilder();
  31. for (Map.Entry<String, ArrayList<String>> entry : phoneBook.entrySet()) {
  32. phoneNumbers.append(entry.getKey() + " ");
  33. for (String number : entry.getValue()) {
  34. phoneNumbers.append(number + " ");
  35. }
  36. phoneNumbers.append("\n");
  37. }
  38. return phoneNumbers.toString();
  39. }
  40. }