您的位置:首页 > 其它

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

2016-08-30 00:50 513 查看
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
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: