Reputation: 1367
I've got something like this:
case class Range(start: String, end: String)
List("s1", "s2", "s3", "s4")
and I want to get:
List(Range("s1","s2"), Range("s2","s3"), Range("s3", "s4"))
For sure I can use classical java for-based solution but I looking for something more elegant.
Upvotes: 1
Views: 171
Reputation: 8663
This does what you expect
list.sliding(2).collect { case List(from, to) => Range(from, to) }.toList
res0: List[Range] = List(Range(s1,s2), Range(s2,s3), Range(s3,s4))
Here is another option
(list zip list.tail) map Range.tupled
Upvotes: 2
Reputation: 588
Here's a simple solution that works regardless of the type of your data (which you can map to whatever you want afterwards):
scala> val l = List("s1", "s2", "s3", "s4")
l: List[String] = List(s1, s2, s3, s4)
scala> l.dropRight(1) zip l.drop(1)
res4: List[(String, String)] = List((s1,s2), (s2,s3), (s3,s4))
Cheers
Upvotes: 1