本文介绍了迭代器和视图之间的区别是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
scala> (1到10).iterator.map {_ * 2} .toList
res1:List [Int] = List(2,4,6,8,10,12,14,16,18,20)
scala> (1到10).view.map {_ * 2} .force
res2:Seq [Int] = Vector(2,4,6,8,10,12,14,16,18,20)$除了使用next,hasNext之外,什么时候应该在迭代器上选择迭代器或者迭代器查看? 解决方案迭代器和视图之间有很大的区别。迭代器仅使用一次,按需计算,而视图使用多次,每次重新计算,但只需要所需的元素。例如:
scala> val list = List(1,2,3).map {x => println(x); x * 2}
1
2
3
list:List [Int] = List(2,4,6)
scala> list(2)
res14:Int = 6
scala> list(2)
res15:Int = 6
scala> val view = List(1,2,3).view.map {x => println(x); x * 2}
view:scala.collection.SeqView [Int,Seq [_]] = SeqViewM(...)
scala> view(2)
3
res12:Int = 6
scala> view(2)
3
res13:Int = 6
scala> val iterator = List(1,2,3).iterator.map {x => println(x); x * 2}
迭代器:Iterator [Int] =非空迭代器
scala> iterator.drop(2).next
1
2
3
res16:Int = 6
scala> iterator.drop(2).next
[Iterator.next](Iterator.scala:29)
(访问完整跟踪的lastException)
scala> (1 to 10).iterator.map{_ * 2}.toList
res1: List[Int] = List(2, 4, 6, 8, 10, 12, 14, 16, 18, 20)
scala> (1 to 10).view.map{_ * 2}.force
res2: Seq[Int] = Vector(2, 4, 6, 8, 10, 12, 14, 16, 18, 20)
Other than using next,hasNext, when should I choose iterator over view or view over iterator?
解决方案 There's a huge difference between iterators and views. Iterators are use once only, compute on demand, while views are use multiple times, recompute each time, but only the elements needed. For instance:
scala> val list = List(1,2,3).map{x => println(x); x * 2}
1
2
3
list: List[Int] = List(2, 4, 6)
scala> list(2)
res14: Int = 6
scala> list(2)
res15: Int = 6
scala> val view = List(1,2,3).view.map{x => println(x); x * 2}
view: scala.collection.SeqView[Int,Seq[_]] = SeqViewM(...)
scala> view(2)
3
res12: Int = 6
scala> view(2)
3
res13: Int = 6
scala> val iterator = List(1,2,3).iterator.map{x => println(x); x * 2}
iterator: Iterator[Int] = non-empty iterator
scala> iterator.drop(2).next
1
2
3
res16: Int = 6
scala> iterator.drop(2).next
[Iterator.next] (Iterator.scala:29)
(access lastException for the full trace)
这篇关于迭代器和视图之间的区别是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!