scala学习笔记:理解stream和view

先来个正常的:

scala> (0 to 5).map((x:Int)=>{println(x);x*2}).foreach(println) 0 1 2 3 4 5 0 2 4 6 8 10

再来个stream版的:

scala> (0 to 5).toStream.map((x:Int)=>{println(x);x*2}).foreach(println) 0 0 1 2 2 4 3 6 4 8 5 10

最后来个view版的:

scala> (0 to 5).view.map((x:Int)=>{println(x);x*2}).foreach(println) 0 0 1 2 2 4 3 6 4 8 5 10

目前看,view和stream的表现一样,那么区别何在呢?观察下一个:

scala> (0 to 5).toStream.map((x:Int)=>{println(x);x*2}) 0 res5: scala.collection.immutable.Stream[Int] = Stream(0, ?) scala> (0 to 5).view.map((x:Int)=>{println(x);x*2}) res6: scala.collection.SeqView[Int,Seq[_]] = SeqViewM(...)

看来stream会优先求第一个值的!这就是区别的全部么?

你可能感兴趣的:(scala学习笔记:理解stream和view)