简体   繁体   中英

Scala iterate over two consecutive elements of a list

How would we iterate over two consecutive elements of a list and apply the difference function For instance I have this:

val list = List(List("Eat", "Drink", "Sleep", "work"), List("Eat", "Sleep", "Dance"))

I want to iterate over these two consecutive elements and calculate the difference

I've tried this but I do not know how to iterate over each two consecutive elements

list.map((a,b) => a.diff(b))

the output should be List("Drink", "work")

If I understand correctly you probably want to iterate over a sliding window.

list.sliding(2).map{
  case List(a, b) => a.diff(b)
  case List(a) => a
}.toList

Alternatively you might also want grouped(2) which partitions the list into groups instead.

def main(args: Array[String]): Unit = {
    val list = List(List("Eat", "Drink", "Sleep", "work"), List("Eat", "Sleep", "Dance"));
    val diff = list.head.diff(list(1))
    println(diff)
  }

In your case, match can work perfectly fine:

val list = List(List("Eat", "Drink", "Sleep", "work"), List("Eat", "Sleep", "Dance"))
list match { case a :: b :: Nil => a diff b}

If the list does not always have 2 items, you should also have a catch-all case in match

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM