Scala学习笔记-06-数据结构-Iterator

Iterator(迭代器)不是一种容器,而是提供了一种按顺序访问容器元素的数据结构。

Iterator提供两种基本操作:

  • next : 返回迭代器中的下一个元素
  • hasNext: 判断迭代器是否还有下一个元素
scala> val it = Iterator("hello","huahua","dog","boy")
it: Iterator[String] = non-empty iterator

scala> while(it.hasNext){
     | println(it.next())
     | }
hello
huahua
dog
boy

Iterable 有两个方法返回迭代器:

  • grouped:返回增量分块
  • sliding:返回滑动元素窗口

grouped:

scala> val list1 = (1 to 20).toList // List继承自Iterable
list1: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20)

scala> val groupedList1 = list1 grouped 3 //返回的是 Iterator
groupedList1: Iterator[List[Int]] = non-empty iterator

scala> groupedList1.next //每次调用next方法均返回3个数据
res102: List[Int] = List(1, 2, 3)

scala> groupedList1.next
res103: List[Int] = List(4, 5, 6)

scala> groupedList1.next
res104: List[Int] = List(7, 8, 9)

sliding:

scala>  val list1 = (1 to 20).toList
list1: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20)

scala> val groupedList1 = list1 sliding 3
groupedList1: Iterator[List[Int]] = non-empty iterator

scala> groupedList1.next
res105: List[Int] = List(1, 2, 3)//每次滑动一个数值

scala> groupedList1.next
res106: List[Int] = List(2, 3, 4)

scala> groupedList1.next
res107: List[Int] = List(3, 4, 5)

---

猜你喜欢

转载自www.cnblogs.com/wooluwalker/p/12304485.html
今日推荐