scala进阶28-实现List高效遍历

时间:2022-09-26 04:00:33
object ListTest {
def main(args: Array[String]): Unit = {
val list = List(1, 3, 4, 5)
increment(list)
increment_MoreEffective(list)
increment_MostEffective(list)
}

/**
* 通过模式匹配加递归的模式实现,效率低,内存消耗巨大
*/
def increment(list: List[Int]) : List[Int] = list match {
case List() => List()
case head :: tail => head + 1 :: increment(tail)
}

/**
* 这种方式实现,会产生很多中间的result
*/
def increment_MoreEffective(list: List[Int]) : List[Int] = {
var result = List[Int]()
for (element <- list) result = result ::: List(element + 1)
result
}

/**
* 借助ListBuffer,最高效的方式
*/
def increment_MostEffective(list: List[Int]) : List[Int] = {
import scala.collection.mutable.ListBuffer
var buffer = new ListBuffer[Int]

for (element <- list) buffer += element + 1
buffer.toList
}
}