假设我有以下数组:
val a = Array(12, 7, 15, 2, 20, 9)
我用一个foreach处理它:
a.foreach { x => // some code }
假设当我处理第二个元素 7 时,我需要有关下一个元素的信息,在本例中为 15。如果我只能访问已处理的事件,如何获取该信息?
您可以在.map
/.foreach
之前使用.sliding(2)
:
scala> a.sliding(2).foreach {
case Array(current, next) => println(s"current is $current, next is $next")
}
current is 12, next is 7
current is 7, next is 15
current is 15, next is 2
current is 2, next is 20
current is 20, next is 9
但请注意,最后一个元素(9
)永远不会被current
到达,因为没有任何next
值可以使用。
顺便说一下,根据您要执行的操作,使用索引访问元素可能会。
Array
具有随机访问功能,因此使用apply
获取元素很便宜。您可以改为循环访问索引。
val a = Array(12, 7, 15, 2, 20, 9)
a.indices.foreach { i =>
if (a(i) == 7 && i + 1 < a.length) {
val next = a(i + 1)
println(s"next element is $next")
}
}
如果你只需要以下元素,你可以压缩list.zip(list.take(1))
,或者一个list.zipWithIndex
将允许你知道你是哪个索引,然后迭代元组。