Exercises Bookstore collect
Use Case 1: Collecting Books with Descriptions
library.collect {
case Book(title, _, _, _, _, Some(description)) => s"$title: $description"
}
Use Case 2: Calculating Total Value of Books
library.foldLeft(0.0)((total, book) => total + book.price)
Use Case 3: Finding the Oldest Book
library.foldLeft(Option.empty[Book]) {
case (None, book) => Some(book)
case (Some(oldest), book) if book.year < oldest.year => Some(book)
case (oldest, _) => oldest
}
Use Case 4: Grouping Books by Decade
library.groupBy(book => (book.year / 10) * 10)
Use Case 5: Counting Books by Category
library.foldLeft(Map.empty[String, Int]) { (counts, book) =>
counts.updated(book.category, counts.getOrElse(book.category, 0) + 1)
}