MaciejF MaciejF - 4 years ago 113
Scala Question

Scala grouping list into list tuples with one shared element

What would be short functional way to split list

List(1, 2, 3, 4, 5) into List((1,2), (2, 3), (3, 4), (4, 5))

Answer Source

You can zip the list with its tail:

val list = List(1, 2, 3, 4, 5)
// list: List[Int] = List(1, 2, 3, 4, 5)

list zip list.tail
// res6: List[(Int, Int)] = List((1,2), (2,3), (3,4), (4,5))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download