Exercises Bookstore collect
The Bookstore
case class Author(name: String, nationality: String)
case class Book(title: String, author: Author, year: Int, category: String, price: Double, description: Option[String])
val authors = List(
Author("George Orwell", "British"),
Author("Harper Lee", "American"),
Author("F. Scott Fitzgerald", "American"),
Author("Aldous Huxley", "British"),
Author("Herman Melville", "American"),
Author("J.D. Salinger", "American"),
Author("Yuval Noah Harari", "Israeli")
)
val library = List(
Book("1984", authors(0), 1949, "Dystopian", 15.99, Some("A dystopian social science fiction novel and cautionary tale.")),
Book("To Kill a Mockingbird", authors(1), 1960, "Fiction", 10.99, Some("A novel about the serious issues of rape and racial inequality.")),
Book("The Great Gatsby", authors(2), 1925, "Classic", 8.99, Some("A story of the mysteriously wealthy Jay Gatsby and his love for Daisy Buchanan.")),
Book("Brave New World", authors(3), 1932, "Dystopian", 12.99, None),
Book("Moby Dick", authors(4), 1851, "Classic", 9.99, Some("The narrative of Captain Ahab's obsessive quest to kill the giant white sperm whale Moby Dick.")),
Book("The Catcher in the Rye", authors(5), 1951, "Fiction", 14.99, Some("A novel about teenage rebellion and alienation."))
)
Use Case 1: Collecting Books with Descriptions
Objective: Extract the titles and descriptions of books that have descriptions.
def collectBooksWithDescriptions(library: List[Book]): List[String] = {
// TODO
}
val booksWithDescriptions = collectBooksWithDescriptions(library)
booksWithDescriptions.foreach(println)
Use Case 2: Calculating Total Value of Books
Objective: Calculate the total value of all books in the library using foldLeft.
def calculateTotalValue(library: List[Book]): Double = {
// TODO
}
val totalValue = calculateTotalValue(library)
println(s"Total value of books: $$${totalValue}")
Use Case 3: Finding the Oldest Book
Objective: Find the oldest book in the library using foldLeft.
def findOldestBook(library: List[Book]): Option[Book] = {
// TODO
}
val oldestBook = findOldestBook(library)
oldestBook match {
case Some(book) => println(s"Oldest book: ${book.title}, published in ${book.year}")
case None => println("No books in the library")
}
Use Case 4: Grouping Books by Decade
Objective: Group books by the decade they were published using collect.
def groupBooksByDecade(library: List[Book]): Map[Int, List[Book]] = {
// TODO
}
val booksByDecade = groupBooksByDecade(library)
booksByDecade.foreach { case (decade, books) =>
println(s"$decade:")
books.foreach(book => println(s" ${book.title}"))
}
Use Case 5: Counting Books by Category
Objective: Count the number of books in each category using foldLeft.
def countBooksByCategory(library: List[Book]): Map[String, Int] = {
// TODO
}
val booksCountByCategory = countBooksByCategory(library)
booksCountByCategory.foreach { case (category, count) =>
println(s"$category: $count books")
}