Simple Phonebook

PhoneBook.java 1.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import java.util.HashSet;
  2. import java.util.Iterator;
  3. import java.util.Map;
  4. import java.util.Map.Entry;
  5. import java.util.Set;
  6. import java.util.TreeMap;
  7. /**
  8. * Created by leon on 1/23/18.
  9. */
  10. public class PhoneBook {
  11. String name;
  12. String number = "";
  13. Map<String, String> yellowPages = new TreeMap<String, String>();
  14. public PhoneBook(){
  15. }
  16. public void add(String name, String phoneNumber){
  17. yellowPages.put(name, phoneNumber);
  18. }
  19. public void remove(String name) {
  20. yellowPages.remove(name);
  21. }
  22. public String lookUp(String name) {
  23. String number = yellowPages.get(name);
  24. return number;
  25. }
  26. public int getSize(){
  27. return yellowPages.size();
  28. }
  29. public String reverseLookUp(String value) {
  30. String key = "";
  31. for(Map.Entry entry : yellowPages.entrySet())
  32. if(value.equals(entry.getValue())){
  33. key = entry.getKey().toString();
  34. }
  35. return key;
  36. }
  37. public String display() {
  38. Set set = yellowPages.entrySet();
  39. Iterator it = set.iterator();
  40. StringBuilder answerBuild = new StringBuilder();
  41. while(it.hasNext()) {
  42. Map.Entry x = (Map.Entry)it.next();
  43. answerBuild.append(x.getKey() + " : " + x.getValue());
  44. }
  45. String answer = answerBuild.toString();
  46. return answer;
  47. }
  48. }