Build a simple PhoneBook program.

PhoneBook.java 2.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. import java.util.*;
  2. import java.util.List;
  3. import java.util.Arrays;
  4. import java.util.Iterator;
  5. /**
  6. * Created by leon on 1/23/18.
  7. */
  8. public class PhoneBook {
  9. String name;
  10. String phoneNumber;
  11. TreeMap<String,ArrayList<String>> directory = new TreeMap<String,ArrayList<String>>();
  12. HashMap<ArrayList<String>,String> reverseDirectory = new HashMap<ArrayList<String>,String>();
  13. public PhoneBook(){
  14. }
  15. public TreeMap getDirectory(){
  16. return directory;
  17. }
  18. public HashMap<ArrayList<String>, String> invertMap() {
  19. for(String k: directory.keySet()){
  20. reverseDirectory.put(directory.get(k), k);
  21. }
  22. return reverseDirectory;
  23. }
  24. public TreeMap add(String name, ArrayList<String> phoneNumber){
  25. directory.put(name, phoneNumber);
  26. return directory;
  27. }
  28. public TreeMap removeRecord(String name){
  29. directory.remove(name);
  30. return directory;
  31. }
  32. public ArrayList<String> lookUp(String name){
  33. return directory.get(name);
  34. }
  35. public String reverseLookUp(String phoneNumber){
  36. this.invertMap();
  37. String answer = "";
  38. for(ArrayList<String> element: reverseDirectory.keySet()){
  39. if(arrayContains(element, phoneNumber) == true){
  40. answer = reverseDirectory.get(element);
  41. }
  42. }
  43. return answer;
  44. }
  45. public String display(){
  46. StringBuilder print = new StringBuilder("");
  47. for(String key : directory.keySet()){
  48. print.append(key + " " + printArray(directory.get(key)) + "\n");
  49. }
  50. return print.toString();
  51. }
  52. public String printArray(ArrayList<String> array){
  53. String result = String.join(", ", array);
  54. return result;
  55. }
  56. public boolean arrayContains(ArrayList<String> list, String phoneNumber){
  57. boolean correct = false;
  58. for(String element : list){
  59. if(phoneNumber.equals(element)){
  60. correct = true;
  61. break;
  62. }
  63. }
  64. return correct;
  65. }
  66. public TreeMap remove(String name, String phoneNumber){
  67. Iterator search = directory.get(name).iterator();
  68. while(search.hasNext()){
  69. if(search.next().equals(phoneNumber)){
  70. search.remove();
  71. break;
  72. }
  73. }
  74. return directory;
  75. }
  76. }