Scala: Get Items from Seq by given index (all the items above given index)

StackOverflow https://stackoverflow.com/questions/18133727

  •  24-06-2022
  •  | 
  •  

Вопрос

I am new to scala, the way I understood Seq is that its an ordered list. So I was wanted to see if I can get all the items based on a given index where retrieved items index is lesser than the given items index.

Lets say I have Seq:

scala> val s = Seq(1, 2, 34 ,44 )
s: Seq[Int] = List(1, 2, 34, 44)

Given index index as 3rd item I was expecting to get all the items(values) that has a lower index position than the given index.

Keep this in mind I wrote the following and Looks like I am wrong.

scala> val x = s.map {
     | id => id < s.indexOf(3) }
x: Seq[Boolean] = List(false, false, false, false)

What what I want is Seq(1,2,34) as the output because if of those element's index is less than the index of 44.

Whats the best way to do this?

Это было полезно?

Решение

s.take(3) will take the first three elements of the sequence, i.e. all elements whose index is smaller than 3 (index counts from zero).

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top