Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Exercises Bookstore filter map

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: Finding Books by a Specific Author

library.filter(_.author.name == authorName)

Use Case 2: Filtering Books Based on Price

library.filter(book => book.price >= minPrice && book.price <= maxPrice)

Use Case 3: Filtering Books by Category

library.filter(_.category == category)

Use Case 4: Displaying Book Titles with Prices

  library.map(book => s"${book.title} - $${book.price}")

Use Case 5: Finding Books Published After a Certain Year

  library.filter(_.year > year)

Use Case 6: Creating a Summary Description for Books

  library.map(book => s"${book.title} by ${book.author.name} [${book.category}]")

Use Case 7: Finding Discounted Books

 library.map(book => (book.title, book.price * (1 - discountRate)))