1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586 |
- import java.util.Map;
- import java.util.*;
- public class PhoneBook {
- Map<String,List<String>> phoneBook = new TreeMap<String,List<String>>();
-
- public PhoneBook(){
-
- }
-
- public void addEntrant(String name, String...phoneNumber){
- String checkName = lookup(name);
- if(checkName == null){
- phoneBook.put(name, Arrays.asList(phoneNumber));
- } else {
- System.out.println("Error, user already exists");
- }
- }
-
- public void addNumber(String name, String newNumber){
- String checkName = lookup(name);
- if(checkName == null){
- addEntrant(name, newNumber);
- } else {
- List<String> newList = new ArrayList<>(phoneBook.get(name));
- newList.add(newNumber);
- phoneBook.put(name, newList);
- }
- }
-
- public void removeNumber(String name, String numberToDelete){
- String checkName = lookup(name);
- if(checkName == null){
- System.out.println("User does not exist");
- } else {
- List<String> newList = new ArrayList<>(phoneBook.get(name));
- ListIterator<String> pbIterator = newList.listIterator();
- while(pbIterator.hasNext()){
- if(pbIterator.next().equals(numberToDelete)){
- pbIterator.remove();
- }
- }
- phoneBook.put(name, newList);
- }
- }
-
- public void removeEntrant(String name){
- phoneBook.remove(name);
- }
-
- public String lookup(String name){
- if (phoneBook.get(name) == null){
- return null;
- }
- StringBuilder numbersList = new StringBuilder();
- int counter = 0;
- for(String number: phoneBook.get(name)){
- numbersList.append(number);
- counter++;
- if(counter != phoneBook.get(name).size()){
- numbersList.append(", ");
- }
- }
- return numbersList.toString();
- }
-
- public String reverseLookup(String phoneNumber){
- for(Map.Entry<String, List<String>> element: phoneBook.entrySet()){
- String key = element.getKey();
- for(String number: phoneBook.get(key)){
- if(number.equals(phoneNumber)){
- return key;
- }
- }
- }
- return "This number does not belong to anyone";
- }
-
- public void display(){
- for(Map.Entry<String, List<String>> element: phoneBook.entrySet()){
- String key = element.getKey();
- List<String> value = element.getValue();
- System.out.println( key + ":" + value);
- }
- }
- }
|