I have a List
val family=List("1","2","11","12","21","22","31","33","41","44","51","55")
i want to take its first n elements but the problem is that parents
size is not fixed.
val familliar=List("1","2","11") //n=3
Method #1 : Using sorted() + lambda The combination of above functionality can be used to perform this particular task. In this, we just employ sorted function with reverse flag true, and print the top N elements using list slicing.
Use the Array. slice() method to get the first N elements of an array, e.g. const first3 = arr. slice(0, 3) . The slice() method will return a new array containing the first N elements of the original array.
The format for list slicing is [start:stop:step]. start is the index of the list where slicing starts. stop is the index of the list where slicing ends. step allows you to select nth item within the range start to stop.
How to extract the first n values of all elements of a list in R? To extract the first n values of all elements of a list in R, we can follow the below steps − First of all, create a list. Then, use head function with sapply function to extract the first n values of all elements in the list.
How to get first n elements of a list in Python. In this tutorial, we are going to learn about how to get the first n elements of a list in Python. Consider, we have the following list: To access the first n elements from a list, we can use the slicing syntax [ ] by passing a 0:n as an arguments to it . 0 is the start index (it is inculded).
To access the first n elements from a list, we can use the slicing syntax [ ] by passing a 0:n as an arguments to it . 0 is the start index (it is inculded). n is end index (it is excluded). Here is an example, that gets the first 3 elements from the following list:
To access the first n elements of an array, we can use the built-in slice () method by passing 0, n as an arguments to it. n is the number of elements we need to get from an array, 0 is the first element index. Here is an example, that gets the first 2 elements of an array:
You can use take
scala> val list = List(1,2,3,4,5,6,7,8,9) list: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9) scala> list.take(3) res0: List[Int] = List(1, 2, 3)
List(1,2,3).take(100) //List(1,2,3)
The signature of take will compare the argument with index, so the incremental index will never more than argument
The signature of take
override def take(n: Int): List[A] = {
val b = new ListBuffer[A]
var i = 0
var these = this
while (!these.isEmpty && i < n) {
i += 1
b += these.head
these = these.tail
}
if (these.isEmpty) this
else b.toList
}
Use take
:
val familliar = family.take(3)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With