Simple Phonebook

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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 phoneNumber = "";
  13. Map<String, String> phoneBook = new TreeMap<String, String>();
  14. public PhoneBook() {
  15. }
  16. public void add(String name, String phoneNumber) {
  17. phoneBook.put(name, phoneNumber);
  18. }
  19. public void remove(String name) {
  20. phoneBook.remove(name);
  21. }
  22. public String lookup(String name) {
  23. String phoneNumber = phoneBook.get(name);
  24. return phoneNumber;
  25. }
  26. public String reverseLookup(String value){
  27. String key = "";
  28. for(Map.Entry entry : phoneBook.entrySet())
  29. if (value.equals(entry.getValue())) {
  30. key = entry.getKey().toString();
  31. }
  32. return key;
  33. }
  34. public String display() {
  35. Set set = phoneBook.entrySet();
  36. Iterator iter = set.iterator();
  37. StringBuilder answer = new StringBuilder();
  38. while(iter.hasNext()) {
  39. Map.Entry i = (Map.Entry)iter.next();
  40. answer.append(i.getKey() + " : " + i.getValue());
  41. }
  42. String result = answer.toString();
  43. return result;
  44. }
  45. public int getSize() {
  46. return phoneBook.size();
  47. }
  48. }