Search code examples
listscalaunzipsliding

Group list by given occurrence in Scala


I have a list of strings that I'm trying to split into separate lists sequentially, grouping the 4th occurrence i.e. this list:

val data = List("1", "2", "3", "4", "5", "6", "7", "8") 

should be grouped as

val list1 = List("1", "5")
val list2 = List("2", "6")
val list3 = List("3", "7")
val list4 = List("4", "8")

I'm not sure if I am trying to overcomplicate this but the only way I can think is to first group the elements using sliding e.g.:

data.sliding(4,4).toList 

results in

List(List(1, 2, 3, 4), List(5, 6, 7, 8))

and then to implement my own unzip method that would group the above as my desired output.

Please can someone let me know if there is an easier way of doing this?


Solution

  • You can use .transpose on the list .sliding generates:

    scala> val data = List("1", "2", "3", "4", "5", "6", "7", "8") 
    data: List[String] = List(1, 2, 3, 4, 5, 6, 7, 8)
    
    scala> data.sliding(4, 4).toList
    res1: List[List[String]] = List(List(1, 2, 3, 4), List(5, 6, 7, 8))
    
    scala> data.sliding(4, 4).toList.transpose
    res2: List[List[String]] = List(List(1, 5), List(2, 6), List(3, 7), List(4, 8))