Scala list take() operation with examples

 150 total views,  1 views today

Welcome to Scala series. In this tutorial, you will learn about the Scala List take() operation with examples.

Scala take() operation allows us to take first N elements in the collection. take() operation will return new collection with first N elements.

Scala take() operation is applicable to all types of Scala collections.

take() Syntax

def take(n: Int): List[A]

Selects the first n elements.

n - the number of elements to take from this list.
returns - a list consisting only of the first n elements of this list, or else the whole list, if it has less than n elements. If n is negative, returns an empty list.

Scala List take() examples

In this take() example, we have created a list and applied take() method to get the first 3 elements.

take() will always return a new collection with first N elements. i.e., it will take elements from left to right.

object TakeTest {

  def main(args: Array[String]): Unit = {

    //Create a list
    var list = List(1, 2, 3, 4, 5, 6, 7, 8);

    //Apply take() and print collection
    list.take(3).foreach(println)

  }
}

Output

1
2
3

Let us see another take() example where we give N as 10 but the size of the is just 8.

object Taketest {

  def main(args: Array[String]): Unit = {

    //Create a list
    var list = List(1, 2, 3, 4, 5, 6, 7, 8);

    //Apply take() and print collection
    list.take(10).foreach(println)

  }
}

Output

1
2
3
4
5
6
7
8

Check out these links to learn to about takeRight() and takeWhile() operations.

ReferencesScala take() operation

I hope you like this tutorial and you were able to understand the Scala list take() operation with examples.

Would you like to learn on Scala features, please check out Scala – a complete guide series. In this tutorial guide, you will useful Scala functions that can be applied to the collection.

Thanks for reading and please give us a thumb up and comment below.

Tags :

About the Author

Rajasekar

Hey There, My name is Rajasekar and I am the author of this site. I hope you are liking my tutorials and references. Programming and learning new technologies are my passion. The ultimate idea of this site is to share my knowledge(I am still a learner :)) and help you out!. Please spread your words about us (staticreference.com) and give a thumbs up :) Feel free to contact me for any queries!.