Build a simple PhoneBook program.

PhoneBook.java 1.9KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /**
  2. * Created by leon on 1/23/18.
  3. */
  4. import java.util.*;
  5. import java.lang.*;
  6. public class PhoneBook {
  7. Map<String, ArrayList<String>> phoneBook = new TreeMap<String, ArrayList<String>>();
  8. public PhoneBook(){
  9. }
  10. public ArrayList<String> add(String name, String phoneNumber){
  11. ArrayList<String> numbers = new ArrayList<>();
  12. if(phoneBook.containsKey(name)) numbers = phoneBook.get(name);
  13. numbers.add(phoneNumber);
  14. add(name, numbers);
  15. return phoneBook.get(name);
  16. // phoneBook.put(name, phoneNumber);
  17. }
  18. public ArrayList<String> add(String name, ArrayList<String> phoneNumbers){
  19. phoneBook.put(name, phoneNumbers);
  20. return phoneBook.get(name);
  21. }
  22. public ArrayList<String> remove(String name){
  23. phoneBook.remove(name);
  24. return phoneBook.get(name);
  25. }
  26. public ArrayList<String> lookUp(String name){
  27. ArrayList<String> number = new ArrayList<>();
  28. for(Map.Entry<String, ArrayList<String>> book: phoneBook.entrySet()){
  29. if(book.getKey().equals(name)){
  30. number = book.getValue();
  31. }
  32. }
  33. return number;
  34. }
  35. public String reverseLookUp(ArrayList<String> phoneNumber){
  36. String name = null;
  37. for(Map.Entry<String, ArrayList<String>> book: phoneBook.entrySet()){
  38. if(book.getValue().equals(phoneNumber)){
  39. name = book.getKey();
  40. }
  41. }
  42. return name;
  43. }
  44. public void display(){
  45. for(Map.Entry<String, ArrayList<String>> book: phoneBook.entrySet()){
  46. System.out.println(book.getKey());
  47. for(String num: book.getValue()){
  48. System.out.println("- "+ num);
  49. }
  50. }
  51. }
  52. public int size(){
  53. return phoneBook.size();
  54. }
  55. }