Java Guild Meeting 5/2018

Gi11i4m
78.4K views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

Exercises

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

Exercise 1:

Implement findPhoneNumberByName and findNameByPhoneNumber in PhoneBook class that returns an optional. An empty optional must be returned if nothing is found.

Write the implementation

Exercise 2:

Implement findPhoneNumberByNameAndPunishIfNothingFound in PhoneBookCrawler that uses an implementation of the PhoneBook class. Punish with an IllegalArgumentException and message "No phone number found".

Write the implementation

Exercise 3:

Implement findPhoneNumberByNameAndPrintPhoneBookIfNothingFound in PhoneBookCrawler that uses the implementation from exercise 1

Write the implementation

Exercise 4

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.

Write the implementation

Exercise 5

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

Write the implementation

Exercise 6

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.

Write the implementation

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.

Open Source Your Knowledge: become a Contributor and help others learn. Create New Content