The exercises for optionals will focus around a PhoneBook class. The phone book already has some initial values:
- Jos de Vos
- An de Toekan
- Kris de Vis
Implement findPhoneNumberByName and findNameByPhoneNumber in PhoneBook class that returns an optional. An empty optional must be returned if nothing is found.
Implement findPhoneNumberByNameAndPunishIfNothingFound in PhoneBookCrawler that uses an implementation of the PhoneBook class. Punish with an IllegalArgumentException and message "No phone number found".
Implement findPhoneNumberByNameAndPrintPhoneBookIfNothingFound in PhoneBookCrawler that uses the implementation from exercise 1
Did you receive 1 or 2 Hello messages from the PhoneBook's toString method when you ran the tests? If you received 2 Hello messages, reimplement it so that you receive only 1 Hello message after running the tests. If you received just 1 Hello message, reimplement exercise 3 to have it actually printed twice.
After the 2 previous exercises, you should now know the difference between using the orElse and orElseGet methods. Optionals also work nicely with streams Can you reimplement exercise 2 using streams instead of using PhoneBook's findPhoneNumberByName
Implement findPhoneNumberByNameOrNameByPhoneNumber in PhoneBookCrawler class. First search the phone book by name. If that returns nothing search the phone book by phone number. If that still returns nothing return the phone number of Jos de Vos.
The exercises focused on Java 8 Optional features. Java 9 has introduced the or method that should allow an easier implementation for the last exercise.