Dividing data into subsets
A common data-processing task is to divide a collection of data into subsets. In this recipe, we are going to explore standard library functions that allow us to buffer a collection into smaller chunks. Let's say we have a list containing a large number of Message
type objects and we would like to transform it into collections of sub-lists of a constant size. For example, the transformation would take the original collection of n elements:
[mssg_1, mssg_2, mssg_3, mssg_4, mssg_5, mssg_6, mssg_7, ..., mssg_n]
And it would then split it into a collection of four element subsets:
[[mssg_1, mssg_2, mssg_3, mssg_4], ..., [mssg_n-3, mssg_n-2, mssg_n-1, mssg_n]]
Getting ready
Let's start by declaring the Message
class that we are going to use in the following recipe:
data class Message(val text: String, val time: Instant = Instant.now())
Let's declare the messages
variable that stores the sample data:
val messages = listOf( Message("Any plans for the evening?"), ...