Last modification: 03/12/16
The Book
class
Create a Book
class. Each book has an author, title and price (in dollars).
Add the fields to the class, make them public and read only.
Add a constructor to the class that takes the author, title and price as argument and initializes the fields.
Override the toString()
method such as it produces a string similar to Book[<author>: <title> (<price>)]
.
Sort by book’s price
Create a BookByPrice
class that defines an ordering on books based on title. The class implements the Comparator<Book>
interface and its compare()
method.
Sort by book’s title
Create a BookByTitle
class that defines an ordering on books based on title. The class also implements the Comparator<Book>
interface and its compare()
method.
The BookDemo
class
Create a main()
method that creates a list of books and sorts it by price in an ascending order using the List.sort()
or Collections.sort()
method and print the list. Then sort in a descending order using Collections.reverseOrder()
and print the list.
Sort the books by title as well.
Modify your main()
method such as it uses an anonymous function to sort by price or title instead of an object of above classes.
Names of expensive books
Modify your main()
method such as it filters books keeping books cost more than $20.
Convert the list into a java.stream.Stream
using List.stream()
and use filter()
, and map()
. Use collect(Collectors.toList())
to convert the stream back into a list.
Finding a book
Find a book with a given title in your list of books. Use a filter()
with combination of a findFirst()
on a stream.
The result of the findFirst()
is an Optional<Book>
object which is basically a box that may be empty.