Categories
Tech

Scala Saturday – The Stream.drop Method

The opposite of Stream.take is Stream.drop. Stream.drop, as the name suggests, skips the first n items of the sequence and returns a new sequence that starts with element n + 1:

val xs = (1 to 10).toStream
val dropped5 = xs drop 5
// dropped5: scala.collection.immutable.Stream[Int] =
//   Stream(6, 7, 8, 9, 10)

One of most obvious applications of Stream.drop is to pair it with Stream.take to page through a set of records. Perhaps you have a list of books:

case class Book(title: String, author: String)

val books = Stream(
  Book("Wuthering Heights", "Emily Bronte"),
  Book("Jane Eyre", "Charlotte Bronte"),
  Book("Agnes Grey", "Anne Bronte"),
  Book("The Scarlet Letter", "Nathaniel Hawthorne"),
  Book("Silas Marner", "George Eliot"),
  Book("1984", "George Orwell"),
  Book("Billy Budd", "Herman Melville"),
  Book("Moby Dick", "Herman Melville"),
  Book("The Great Gatsby", "F. Scott Fitzgerald"),
  Book("Tom Sawyer", "Mark Twain")
)

If each page shows three books, and the user wants to see the records on page three, skip the first two pages’ worth of records, and take the next three records:

val perPage = 3
val page = 3
val records = books.drop((page - 1) * perPage)
                .take(perPage)
// records: scala.collection.immutable.Stream[Book] = 
//   Stream(Book(Billy Budd,Herman Melville), 
//     Book(Moby Dick,Herman Melville), 
//     Book(The Great Gatsby,F. Scott Fitzgerald))

Fortunately, like Stream.take, if you ask the sequence for more elements than it contains, you simply get an empty stream:

val empty= (1 to 5).toStream drop 6
// empty: scala.collection.immutable.Stream[Int] =
//   Stream()

One reply on “Scala Saturday – The Stream.drop Method”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.