Take is used to take the first n elements of a collection. The formal definition of using take is as follows:
def take(n: Int): Traversable[A]
Let's see an example as follows:
// Given an infinite recursive method creating a stream of odd numbers.
def odd: Stream[Int] = {
def odd0(x: Int): Stream[Int] =
if (x%2 != 0) x #:: odd0(x+1)
else odd0(x+1)
odd0(1)
}// Get a list of the 5 first odd numbers.
odd take (5) toList
You will get the following output:
res5: List[Int] = List(1, 3, 5, 7, 9)
In Scala, if want to partition specific collections into a map of an other Traversable collection according to a specific partitioning function, you can use the groupBy() method. In the next subsection, we will show some examples of using groupBy().