Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala list take with offset

For example I have val source = List("1", "2", "3", "4", "5", "6", "7") and I need get 3 elements start with second element. expected List("2","3") or List("3","4"). Is there any methods or any data structure with this ability?

like image 887
mechanikos Avatar asked Mar 03 '26 18:03

mechanikos


2 Answers

I think slice is exactly what you're looking for

scala> val source = List("1", "2", "3", "4", "5", "6", "7")
source: List[String] = List(1, 2, 3, 4, 5, 6, 7)

scala> source.slice(2, 4)
res0: List[String] = List(3, 4)
like image 134
serejja Avatar answered Mar 05 '26 09:03

serejja


Use combinations of drop and take methods:

source.drop(2).take(3) // List(3, 4, 5)
  • drop - skip first n elements
  • take - grab n elements
like image 44
Sergii Lagutin Avatar answered Mar 05 '26 07:03

Sergii Lagutin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!