scala迭代器
Scala Option can be defined as container that holds zero or more elements of the given type. The option[T]
can return Some[T]
or None
object which represents a missing value.
Scala选项可以定义为包含零个或多个给定类型元素的容器。 option[T]
可以返回表示缺少值的Some[T]
或None
对象。
Consider an example of how to create a option;
考虑一个如何创建一个选项的例子。
val msg : Option[String] = Some("Option is a Scala collection")
Consider an example of how to assign a none value;
考虑一个如何分配无值的例子。
val msg : Option[String] = None
Create Student.scala class in Scala IDE as;
在Scala IDE中将Student.scala类创建为;
case class Student(
id: Int,
Name: String,
marks: Float,
gender: Option[String])
object TestStudent {
private val students = Map(1 -> Student(10, "John", 62.5f, Some("male")),
2 -> Student(12, "Adam", 70.5f, Some("female")))
def findById(id: Int): Option[Student] = students.get(id)
def findAll = students.values
}
Here we are defining a class student with id, name, marks and gender as attributes. Create an object TestStudent
in which we define findById
method that returns an Option of type Student and findAll
which retrieves the values from students map.
在这里,我们定义了一个以id,姓名,标记和性别为属性的班级学生。 创建一个对象TestStudent
在其中定义findById
方法,该方法返回Student类型的Option,而findAll
从学生映射中检索值。
Now create another object s1.scala as
S1.scala
现在创建另一个对象s1.scala作为
S1.scala
object S1 {
def main(args: Array[String]) {
val st1 = TestStudent.findById(2)
if (st1.isDefined) {
println(st1.get.id)
println(st1.get.Name)
println(st1.get.marks)
}
}
}
Below image shows the output produced when we run S1 as scala application.
下图显示了将S1作为scala应用程序运行时产生的输出。
Let’s look at some other examples for Scala Option.
让我们看看Scala Option的其他示例。
指定默认值 (Specifying default value)
The default value can be specified using getOrElse
method.
可以使用getOrElse
方法指定默认值。
For example create a scala object as below:
GetorElse.scala
例如,创建一个scala对象,如下所示:
GetorElse.scala
object GetorElse {
def main(args: Array[String]) {
val stud = Student(14, "Chris", 45f, None)
println(stud.gender.getOrElse("Gender not specified"))
}
}
Below image shows the output produced as default value since gender was missing.
下图显示了由于缺少性别而产生的默认值输出。
The gender is specified as None while creating stud instance and hence the message “Gender not specified” is printed.
创建螺柱实例时将性别指定为“无”,因此将显示消息“未指定性别”。
模式匹配 (Pattern Matching)
The optional values can be taken apart through pattern matching.
可选值可以通过模式匹配分开。
For instance:
例如:
KeyPatternMatch.scala
KeyPatternMatch.scala
object KeyPatternMatch {
def main(args: Array[String]) {
val student = Map(12 -> "Anderson", 14 -> "Reena")
println("Student Name with id 12 : " + displaykey(student.get(12)))
println("Student Name with id 14 : " + displaykey(student.get(14)))
}
def displaykey(a: Option[String]) = a match {
case Some(t) => t
case None => "?"
}
}
Output:
输出:
Student Name with id 12 : Anderson
Student Name with id 14 : Reena
isEmpty() method
isEmpty()方法
The isEmpty()
method is used to check whether the option returns empty or not.
isEmpty()
方法用于检查选项是否返回空。
For example;
Empty.scala
例如;
Empty.scala
object Empty {
def main(args: Array[String]) {
val x: Option[Int] = Some(5)
val y: Option[Int] = None
println("Check X is Empty: " + x.isEmpty)
println("Check Y is Empty: " + y.isEmpty)
}
}
It produces below output.
它产生以下输出。
Check X is Empty: false
Check Y is Empty: true
有用的期权方法 (Useful Option Methods)
def isDefined: Boolean → Returns true if the option is an instance of Some, else returns false
def isDefined:布尔值 →如果选项是Some的实例,则返回true,否则返回false
def or Null → Returns the option’s value if it is nonempty, or null if it is empty.
def或Null →如果选项为非空,则返回其值;如果为空,则返回null。
def isEmpty: Boolean → Returns true if the option is None, false otherwise.
def isEmpty:布尔值 →如果选项为None,则返回true,否则返回false。
def get: X → Returns the option’s value.
def get:X →返回选项的值。
def foreach[Y](f: (Z) => Y): Unit → Apply the given procedure f to the option’s value, if it is nonempty.
def foreach [Y](f:(Z)=> Y):单位 →如果给定过程f为非空值,则将其应用于该选项的值。
Scala迭代器 (Scala Iterators)
An Iterator allows user to iterate over the collection thereby accessing all the elements. The core operations of iterator are next
and hasNext
. The next elements return the successive element and hasNext checks whether the element is present or not.
迭代器允许用户遍历集合,从而访问所有元素。 迭代器的核心操作是next
和hasNext
。 next元素返回后继元素,并且hasNext检查该元素是否存在。
For example;
例如;
Create the scala object Iterator.scala
as
Iterator.scala
将scala对象Iterator.scala
创建为
Iterator.scala
object Car {
def main(args: Array[String]) {
val car = Iterator("Santro", "Punto", "WagonR", "Polo", "Audi")
while (car.hasNext) {
println(car.next())
}
}
}
Output:
输出:
Santro
Punto
WagonR
Polo
Audi
迭代器的长度 (Length of Iterator)
The size or length methods can be used to find the number of the elements in the iterator.
大小或长度方法可用于查找迭代器中元素的数量。
For example,
CarLength.scala
例如,
CarLength.scala
object CarLength {
def main(args: Array[String]) {
val c1 = Iterator("Santro", "Punto", "WagonR", "Polo", "Audi")
val c2 = Iterator("Volkswagen", "Alto", "Xylo", "Innova")
println("Iterator c1 : " + c1.size)
println("Length of c2 : " + c2.length)
}
}
Output:
输出:
Iterator c1 : 5
Length of c2 : 4
查找最小和最大元素 (Finding Minimum and Maximum Elements)
The it.min
and it.max
methods are used to find the minimum and maximum elements in the iterator.
使用it.min
和it.max
方法查找迭代器中的最小和最大元素。
Create scala object MinMax.scala
as;
MinMax.scala
将scala对象MinMax.scala
创建为;
MinMax.scala
object MinMax {
def main(args: Array[String]) {
val m1 = Iterator(12,45,67,89)
val m2 = Iterator(44,66,77,88)
println("Smallest element " + m1.min )
println("Largest element " + m2.max )
}
}
Output:
输出:
Smallest element 12
Largest element 88
有用的迭代器方法 (Useful Iterator Methods)
def addString(x: StringBuilder): StringBuilder → Returns the string builder x to which elements were appended.
def addString(x:StringBuilder):StringBuilder →返回附加了元素的字符串生成器x。
def buffered: BufferedIterator[X] → Creates a buffered iterator from this iterator.
def缓冲:BufferedIterator [X] →从此迭代器创建一个缓冲的迭代器。
def foreach(f: (X) => Unit): Unit → Applies a function f to all values produced by this iterator.
def foreach(f:(X)=> Unit):Unit →将函数f应用于此迭代器产生的所有值。
def indexOf(elem: Y): Int → Returns the index of the first occurrence of the specified object in this iterable object.
def indexOf(elem:Y):Int →返回指定对象在此可迭代对象中首次出现的索引。
def product: X → Multiplies the elements of this collection.
def product:X →将这个集合的元素相乘。
That’s all for Scala Option and Iterators, we will look into Scala Traits in the next tutorial.
这就是Scala Option和Iterators的全部内容,我们将在下一个教程中研究Scala特性。
翻译自: https://www.journaldev.com/8082/scala-option-and-iterators-example
scala迭代器