Build a simple PhoneBook program.

PhoneBook.java 1.3KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import java.util.TreeMap;
  2. import java.util.*;
  3. /**
  4. * Created by leon on 1/23/18.
  5. */
  6. public class PhoneBook {
  7. TreeMap<String, ArrayList<String>> pb;
  8. public PhoneBook(){
  9. pb = new TreeMap<>();
  10. }
  11. public void addElement(String name, String phoneNumber){
  12. ArrayList<String> aList = pb.containsKey(name) ? pb.get(name): new ArrayList<String>();
  13. aList.add(phoneNumber + "\n");
  14. pb.put(name, aList);
  15. }
  16. public void remove(String name){
  17. pb.remove(name);
  18. }
  19. public String lookUp(String name){
  20. StringBuilder look = new StringBuilder();
  21. for(String element: this.pb.get(name)){
  22. look.append(element);
  23. }
  24. return look.toString();
  25. }
  26. public String reverseLookup(String phoneNumber){
  27. String gettingThatValue = null;
  28. for(Map.Entry<String,ArrayList<String>> element: pb.entrySet()){
  29. if(element.getValue().contains(phoneNumber)){
  30. gettingThatValue = element.getKey();
  31. break;
  32. }
  33. }
  34. return gettingThatValue;
  35. }
  36. public void display(){
  37. for(Map.Entry<String,ArrayList<String>> element:pb.entrySet()){
  38. System.out.print(element.getKey() + ":" + element.getValue().toString());
  39. }
  40. }
  41. }