12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788 |
- import java.util.*;
-
- /**
- * Created by leon on 1/23/18.
- */
- public class PhoneBook {
- String name;
- String phoneNumber;
- TreeMap<String, ArrayList<String>> phoneBook = new TreeMap<>();
-
- public PhoneBook(TreeMap<String, ArrayList<String>> phoneBook) {
- this.phoneBook = phoneBook;
- }
-
- public PhoneBook(){}
-
- public void add(String name, String phoneNumber){
- ArrayList<String> list;
-
- if (!phoneBook.containsKey(name)) {
- list = new ArrayList<>();
- phoneBook.put(name, list);
- }
- else
- {
- list = phoneBook.get(name);
- list.add(phoneNumber);
- phoneBook.replace(name, list);
- }
- }
-
- public void remove(String name){
- phoneBook.remove(name);
- }
-
- public String lookup(String name){
- ArrayList<String> numbers = phoneBook.get(name);
- StringBuilder sb = new StringBuilder();
-
- for (int i=0; i<numbers.size(); i++) {
- sb.append(numbers.get(i));
- if (i == numbers.size()-1) {
- break;
- } else {
- sb.append(", ");
- }
- }
- sb.append("");
- return sb.toString();
- }
-
- public String reverseLookup(String phoneNumber) {
- for (Map.Entry<String, ArrayList<String>> e : phoneBook.entrySet()) {
- String name = e.getKey();
- ArrayList<String> numbers = e.getValue();
-
- for (String s : numbers) {
- if (s == phoneNumber) {
- return name;
- }
- }
- }
- return "Name not found";
- }
-
- public String display() {
- StringBuilder sb = new StringBuilder();
-
- for (Map.Entry<String, ArrayList<String>> e : phoneBook.entrySet()){
- String name = e.getKey();
- ArrayList<String> numbers = e.getValue();
-
- sb.append(name).append(" ");
-
- for (int i=0; i<numbers.size(); i++) {
- sb.append(numbers.get(i));
- if (i == numbers.size()-1) {
- break;
- } else {
- sb.append(", ");
- }
- }
- sb.append("");
- }
- return sb.toString();
- }
- }
|