Spark记录-Scala集合
Scala列表
Scala列表与数组非常相似,列表的所有元素都具有相同的类型,但有两个重要的区别。 首先,列表是不可变的,列表的元素不能通过赋值来更改。 其次,列表表示一个链表,而数组是平的。
具有类型T的元素的列表的类型被写为List[T]。
尝试以下示例,这里列出了为各种数据类型定义的列表。
// List of Strings
val fruit: List[String] = List("apples", "oranges", "pears")
// List of Integers
val nums: List[Int] = List(1, 2, 3, 4)
// Empty List.
val empty: List[Nothing] = List()
// Two dimensional list
val dim: List[List[Int]] =
List(
List(1, 0, 0),
List(0, 1, 0),
List(0, 0, 1)
)
所有列表都可以使用两个基本构建块定义,尾部为Nil和::,它的发音为cons。 Nil也代表空列表。以上列表可以定义如下。
// List of Strings
val fruit = "apples"::("oranges"::("pears"::Nil))
// List of Integers
val nums = 1::(2::(3::(4::Nil)))
// Empty List.
val empty = Nil
// Two dimensional list
val dim = (1::(0::(0::Nil))) ::
(0::(1::(0::Nil))) ::
(0::(0::(1::Nil)))::Nil
列表基本操作
列表上的所有操作都可以用以下三种方法表示。
| 序号 | 方法 | 描述 |
|---|---|---|
| 1 | head | 此方法返回列表的第一个元素。 |
| 2 | tail | 此方法返回由除第一个之外的所有元素组成的列表。 |
| 3 | isEmpty | 如果列表为空,则此方法返回true,否则返回false。 |
以下示例显示如何使用上述方法。
示例
object Demo {
def main(args: Array[String]) {
val fruit = "apples"::("oranges"::("pears"::Nil))
val nums = Nil
println( "Head of fruit : " + fruit.head )
println( "Tail of fruit : " + fruit.tail )
println( "Check if fruit is empty : " + fruit.isEmpty )
println( "Check if nums is empty : " + nums.isEmpty )
}
}
将上述程序保存在源文件:Demo.scala中,使用以下命令编译和执行此程序。
D:\>scalac Demo.scala
D:\>scala Demo
Head of fruit : apples
Tail of fruit : List(oranges, pears)
Check if fruit is empty : false
Check if nums is empty : true
连接列表
可以使用:::操作符或List.:::()方法或List.concat()方法添加两个或多个列表。 请看下面给出的例子 -
示例
object Demo {
def main(args: Array[String]) {
val fruit1 = "apples"::("oranges"::("pears"::Nil))
val fruit2 = "mangoes"::("banana"::Nil)
// use two or more lists with ::: operator
var fruit = fruit1 ::: fruit2
println( "fruit1 ::: fruit2 : " + fruit )
// use two lists with Set.:::() method
fruit = fruit1.:::(fruit2)
println( "fruit1.:::(fruit2) : " + fruit )
// pass two or more lists as arguments
fruit = List.concat(fruit1, fruit2)
println( "List.concat(fruit1, fruit2) : " + fruit )
}
}
将上述程序保存在源文件:Demo.scala中,使用以下命令编译和执行此程序。
D:\>scalac Demo.scala
D:\>scala Demo
fruit1 ::: fruit2 : List(apples, oranges, pears, mangoes, banana)
fruit1.:::(fruit2) : List(mangoes, banana, apples, oranges, pears)
List.concat(fruit1, fruit2) : List(apples, oranges, pears, mangoes, banana)
创建统一列表
可以使用List.fill()方法创建由零个或多个相同元素的副本组成的列表。 请尝试以下示例程序。
示例
object Demo {
def main(args: Array[String]) {
val fruit = List.fill(3)("apples") // Repeats apples three times.
println( "fruit : " + fruit )
val num = List.fill(10)(2) // Repeats 2, 10 times.
println( "num : " + num )
}
}
将上述程序保存在源文件:Demo.scala中,使用以下命令编译和执行此程序。
D:\>scalac Demo.scala
D:\>scala Demo
fruit : List(apples, apples, apples)
num : List(2, 2, 2, 2, 2, 2, 2, 2, 2, 2)
制表函数
您可以使用一个函数与List.tabulate()方法在列表之前应用于列表的所有元素。它的参数与List.fill类似:第一个参数列表给出要创建的列表的维度,第二个参数列出了列表的元素。唯一的区别是,它不修复元素,而是从函数中计算。
请尝试以下示例程序 -
object Demo {
def main(args: Array[String]) {
// Creates 5 elements using the given function.
val squares = List.tabulate(6)(n => n * n)
println( "squares : " + squares )
val mul = List.tabulate( 4,5 )( _ * _ )
println( "mul : " + mul )
}
}
将上述程序保存在源文件:Demo.scala中,使用以下命令编译和执行此程序。
D:\>scalac Demo.scala
D:\>scala Demo
squares : List(0, 1, 4, 9, 16, 25)
mul : List(List(0, 0, 0, 0, 0), List(0, 1, 2, 3, 4),
List(0, 2, 4, 6, 8), List(0, 3, 6, 9, 12))
反向列表顺序
可以使用List.reverse方法来反转列表的所有元素。以下示例显示了使用情况 -
object Demo {
def main(args: Array[String]) {
val fruit = "apples"::("oranges"::("pears"::Nil))
println( "Before reverse fruit : " + fruit )
println( "After reverse fruit : " + fruit.reverse )
}
}
将上述程序保存在源文件:Demo.scala中,使用以下命令编译和执行此程序。
D:\>scalac Demo.scala
D:\>scala Demo
Before reverse fruit : List(apples, oranges, pears)
After reverse fruit : List(pears, oranges, apples)
Scala列表方法
以下是使用列表时可以使用的重要方法。有关可用方法的完整列表,请查看Scala的官方文档。
| 序号 | 方法 | 描述 |
|---|---|---|
| 1 | def +(elem: A): List[A] |
向列表中添加一个元素 |
| 2 | def ::(x: A): List[A] |
向列表开头位置添加一具元素。 |
| 3 | def :::(prefix: List[A]): List[A] |
在此列表前添加给定列表中的元素。 |
| 4 | def ::(x: A): List[A] |
在列表的开头添加一个元素x |
| 5 | def addString(b: StringBuilder): StringBuilder |
将列表的所有元素附加到字符串构建器。 |
| 6 | def addString(b: StringBuilder, sep: String): StringBuilder |
使用分隔符字符串将列表的所有元素附加到字符串构建器。 |
| 7 | def apply(n: Int): A |
通过列表中的索引选择一个元素。 |
| 8 | def contains(elem: Any): Boolean |
测试列表是否包含给定元素值。 |
| 9 | def copyToArray(xs: Array[A], start: Int, len: Int): Unit |
将列表的元素复制到数组。在给定的数组xs中填充该列表的最多为长度(len)元素,从start位置开始。 |
| 10 | def distinct: List[A] |
从列表中创建一个新的列表,而不会有任何重复的元素。 |
| 11 | def drop(n: Int): List[A] |
返回除了前n个之外的所有元素。 |
| 12 | def dropRight(n: Int): List[A] |
返回除最后n个之外的所有元素。 |
| 13 | def dropWhile(p: (A) => Boolean): List[A] |
删除满足谓词的元素的最长前缀。 |
| 14 | def endsWith[B](that: Seq[B]): Boolean |
测试列表是否以给定的顺序结束。 |
| 15 | def equals(that: Any): Boolean |
任意序列的equals方法,将此序列与其他对象进行比较。 |
| 16 | def exists(p: (A) => Boolean): Boolean |
测试一个谓词是否适用于列表的某些元素。 |
| 17 | def filter(p: (A) => Boolean): List[A] |
返回列表中满足谓词的所有元素。 |
| 18 | def forall(p: (A) => Boolean): Boolean |
测试列表中所有元素的谓词是否成立。 |
| 19 | def foreach(f: (A) => Unit): Unit |
将函数f应用于列表的所有元素。 |
| 20 | def head: A |
选择列表的第一个元素。 |
| 21 | def indexOf(elem: A, from: Int): Int |
在索引位置之后,查找列表中第一个出现值的索引。 |
| 22 | def init: List[A] |
返回除上一个以外的所有元素。 |
| 23 | def intersect(that: Seq[A]): List[A] |
计算列表和另一个序列之间的多集合交集。 |
| 24 | def isEmpty: Boolean |
测试列表是否为空。 |
| 25 | def iterator: Iterator[A] |
在可迭代对象中包含的所有元素上创建一个新的迭代器。 |
| 26 | def last: A |
返回最后一个元素。 |
| 27 | def lastIndexOf(elem: A, end: Int): Int |
查找列表中某些值的最后一次出现的索引; 在给定的结束指数之前或之中。 |
| 28 | def length: Int |
返回列表的长度。 |
| 29 | def map[B](f: (A) => B): List[B] |
通过将函数应用于此列表的所有元素来构建新集合。 |
| 30 | def max: A |
查找最大元素。 |
| 31 | def min: A |
查找最小元素。 |
| 32 | def mkString: String |
显示字符串中列表的所有元素。 |
| 33 | def mkString(sep: String): String |
使用分隔符字符串显示字符串中列表的所有元素。 |
| 34 | def reverse: List[A] |
以相反的顺序返回带有元素的新列表。 |
| 35 | def sorted[B >: A]: List[A] |
根据顺序规则对列表进行排序。 |
| 36 | def startsWith[B](that: Seq[B], offset: Int): Boolean |
测试列表是否包含给定索引处的给定序列。 |
| 37 | def sum: A |
将这个集合所有元素相加。 |
| 38 | def tail: List[A] |
返回除第一个之外的所有元素。 |
| 39 | def take(n: Int): List[A] |
返回第一个“n”个元素。 |
| 40 | def takeRight(n: Int): List[A] |
返回最后的“n”个元素。 |
| 41 | def toArray: Array[A] |
将列表转换为数组。 |
| 42 | def toBuffer[B >: A]: Buffer[B] |
将列表转换为可变缓冲区。 |
| 43 | def toMap[T, U]: Map[T, U] |
将此列表转换为映射。 |
| 44 | def toSeq: Seq[A] |
将列表转换为序列。 |
| 45 | def toSet[B >: A]: Set[B] |
将列表转换为一个集合。 |
| 46 | def toString(): String |
将列表转换为字符串。 |
Scala集合(Set)
Scala Set是相同类型成对的不同元素的集合。换句话说,一个集合是不包含重复元素的集合。 集合有两种:不可变(immutable)和可变(mutable)。可变对象和不可变对象之间的区别在于,当对象不可变时,对象本身无法更改。
默认情况下,Scala使用不可变的集合(Set)。 如果要使用可变集合(Set),则必须明确导入scala.collection.mutable.Set类。 如果要在同一集合中使用可变集合和不可变集合,则可以继续引用不可变集作为集合(Set),但可以将可变集合称为mutable.Set。
// Empty set of integer type
var s : Set[Int] = Set()
// Set of integer type
var s : Set[Int] = Set(1,3,5,7)
// 或者
var s = Set(1,3,5,7)
通过定义一个空集合,类型注释是必要的,因为系统需要将具体的类型分配给变量。
集合基本操作
所有对集合的操作都可以用以下三种方法来表示:
| 序号 | 方法 | 描述 |
|---|---|---|
| 1 | head | 此方法返回列表的第一个元素。 |
| 2 | tail | 此方法返回由除第一个之外的所有元素组成的列表。 |
| 3 | isEmpty | 如果列表为空,则此方法返回true,否则返回false。 |
以下示例显示如何使用上述方法。
示例
object Demo {
def main(args: Array[String]) {
val fruit = Set("apples", "oranges", "pears")
val nums: Set[Int] = Set()
println( "Head of fruit : " + fruit.head )
println( "Tail of fruit : " + fruit.tail )
println( "Check if fruit is empty : " + fruit.isEmpty )
println( "Check if nums is empty : " + nums.isEmpty )
}
}
将上述程序保存在源文件:Demo.scala中,使用以下命令编译和执行此程序。
D:\>scalac Demo.scala
D:\>scala Demo
Head of fruit : apples
Tail of fruit : Set(oranges, pears)
Check if fruit is empty : false
Check if nums is empty : true
连接集合
您可以使用++运算符或Set.++()方法连接两个或多个集合,但是在添加集合时,它将删除重复的元素。
以下是连接两个集合的例子 -
object Demo {
def main(args: Array[String]) {
val fruit1 = Set("apples", "oranges", "pears")
val fruit2 = Set("mangoes", "banana")
// use two or more sets with ++ as operator
var fruit = fruit1 ++ fruit2
println( "fruit1 ++ fruit2 : " + fruit )
// use two sets with ++ as method
fruit = fruit1.++(fruit2)
println( "fruit1.++(fruit2) : " + fruit )
}
}
将上述程序保存在源文件:Demo.scala中,使用以下命令编译和执行此程序。
D:\>scalac Demo.scala
D:\>scala Demo
fruit1 ++ fruit2 : Set(banana, apples, mangoes, pears, oranges)
fruit1.++(fruit2) : Set(banana, apples, mangoes, pears, oranges)
在集合中查找最大值,最小元素
可以使用Set.min方法和Set.max方法来分别找出集合中元素的最大值和最小值。 以下是显示程序的示例。
object Demo {
def main(args: Array[String]) {
val num = Set(5,6,9,20,30,45)
// find min and max of the elements
println( "Min element in Set(5,6,9,20,30,45) : " + num.min )
println( "Max element in Set(5,6,9,20,30,45) : " + num.max )
}
}
将上述程序保存在源文件:Demo.scala中,使用以下命令编译和执行此程序。
D:\>scalac Demo.scala
D:\>scala Demo
Min element in Set(5,6,9,20,30,45) : 5
Max element in Set(5,6,9,20,30,45) : 45
查找交集值
可以使用Set.&或Set.intersect方法来查找两个集合之间的交集(相交值)。尝试以下示例来显示用法。
object Demo {
def main(args: Array[String]) {
val num1 = Set(5,6,9,20,30,45)
val num2 = Set(50,60,9,20,35,55)
// find common elements between two sets
println( "num1.&(num2) : " + num1.&(num2) )
println( "num1.intersect(num2) : " + num1.intersect(num2) )
}
}
将上述程序保存在源文件:Demo.scala中,使用以下命令编译和执行此程序。
D:\>scalac Demo.scala
D:\>scala Demo
num1.&(num2) : Set(20, 9)
num1.intersect(num2) : Set(20, 9)
Scala集方法
有关可用方法的完整列表,请查看Scala的官方文档。
Scala映射
Scala映射(Map)是一组键/值对的对象。 任何值都可以根据键来进行检索。键在映射中是唯一的,但值不一定是唯一的。映射也称为哈希表。映射有两种,不可变的和可变的。可变对象和不可变对象之间的区别在于,当对象不可变时,对象本身无法更改。
默认情况下,Scala使用不可变映射(Map)。如果要使用可变集合(Set),则必须明确导入scala.collection.mutable.Map类。如果想同时使用可变的和不可变映射(Map),那么可以继续引用不可变映射(Map),但是可以将mutable集合引用mutable.Map。
以下是声明不可变映射(Map)的示例声明 -
// Empty hash table whose keys are strings and values are integers:
var A:Map[Char,Int] = Map()
// A map with keys and values.
val colors = Map("red" -> "#FF0000", "azure" -> "#F0FFFF")
在定义空的映射(Map)时,类型注释是必需的,因为系统需要将具体的类型分配给变量。 如果我们要向映射(Map)添加一个键值对,可以使用运算符+,如下所示 -
A + = ('I' -> 1)
A + = ('J' -> 5)
A + = ('K' -> 10)
A + = ('L' -> 100)
集合基本操作
映射(Map)的所有操作都可以用以下三种方法来表示:
| 序号 | 方法 | 描述 |
|---|---|---|
| 1 | keys | 此方法返回包含映射中每个键的迭代。 |
| 2 | values | 此方法返回一个包含映射中每个值的迭代。 |
| 3 | isEmpty | 如果列表为空,则此方法返回true,否则返回false。 |
尝试以下示例程序显示Map方法的用法。
示例
object Demo {
def main(args: Array[String]) {
val colors = Map("red" -> "#FF0000", "azure" -> "#F0FFFF", "peru" -> "#CD853F")
val nums: Map[Int, Int] = Map()
println( "Keys in colors : " + colors.keys )
println( "Values in colors : " + colors.values )
println( "Check if colors is empty : " + colors.isEmpty )
println( "Check if nums is empty : " + nums.isEmpty )
}
}
将上述程序保存在源文件:Demo.scala中,使用以下命令编译和执行此程序。
D:\>scalac Demo.scala
D:\>scala Demo
Keys in colors : Set(red, azure, peru)
Values in colors : MapLike(#FF0000, #F0FFFF, #CD853F)
Check if colors is empty : false
Check if nums is empty : true
连接映射
可以使用++运算符或Map.++()方法连接两个或多个映射,但在添加映射时,它将删除重复的键。
尝试以下示例程序连接两个映射。
以下是连接两个映射的例子 -
object Demo {
def main(args: Array[String]) {
val colors1 = Map("red" -> "#FF0000", "azure" -> "#F0FFFF", "peru" -> "#CD853F")
val colors2 = Map("blue" -> "#0033FF", "yellow" -> "#FFFF00", "red" -> "#FF0000")
// use two or more Maps with ++ as operator
var colors = colors1 ++ colors2
println( "colors1 ++ colors2 : " + colors )
// use two maps with ++ as method
colors = colors1.++(colors2)
println( "colors1.++(colors2)) : " + colors )
}
}
将上述程序保存在源文件:Demo.scala中,使用以下命令编译和执行此程序。
D:\>scalac Demo.scala
D:\>scala Demo
colors1 ++ colors2 : Map(blue -> #0033FF, azure -> #F0FFFF,
peru -> #CD853F, yellow -> #FFFF00, red -> #FF0000)
colors1.++(colors2)) : Map(blue -> #0033FF, azure -> #F0FFFF,
peru -> #CD853F, yellow -> #FFFF00, red -> #FF0000)
打印映射的键和值
可以使用foreach循环迭代映射的键和值。在这里,使用与迭代器相关联的方法foreach来遍历键。 以下是示例程序。
object Demo {
def main(args: Array[String]) {
val colors = Map("red" -> "#FF0000", "azure" -> "#F0FFFF","peru" -> "#CD853F")
colors.keys.foreach{ i =>
print( "Key = " + i )
println(" Value = " + colors(i) )}
}
}
将上述程序保存在源文件:Demo.scala中,使用以下命令编译和执行此程序。
D:\>scalac Demo.scala
D:\>scala Demo
Key = red Value = #FF0000
Key = azure Value = #F0FFFF
Key = peru Value = #CD853F
查找检查映射中的键
可以使用Map.contains方法来测试映射中给定的键是否存在。尝试以下示例程序进行键检查。
object Demo {
def main(args: Array[String]) {
val colors = Map("red" -> "#FF0000", "azure" -> "#F0FFFF", "peru" -> "#CD853F")
if( colors.contains( "red" )) {
println("Red key exists with value :" + colors("red"))
} else {
println("Red key does not exist")
}
if( colors.contains( "maroon" )) {
println("Maroon key exists with value :" + colors("maroon"))
} else {
println("Maroon key does not exist")
}
}
}
将上述程序保存在源文件:Demo.scala中,使用以下命令编译和执行此程序。
D:\>scalac Demo.scala
D:\>scala Demo
Red key exists with value :#FF0000
Maroon key does not exist
Scala元组
Scala元组将固定数量的项目组合在一起,以便它们可以作为一个整体传递。 与数组或列表不同,元组可以容纳不同类型的对象,但它们也是不可变的。
以下是一个存有整数,字符串和控制台(console)的元组的示例。
val t = (1, "hello", Console)
上面是以下语法的简写 -
val t = new Tuple3(1, "hello", Console)
元组的实际类型取决于它包含的数量和元素以及这些元素的类型。 因此,(99,"Luftballons")的类型是Tuple2 [Int,String]。 ('u','r',“the”,1,4,"me")是Tuple6 [Char,Char,String,Int,Int,String]。
元组是类型Tuple1,Tuple2,Tuple3等等。目前在Scala中只能有22个上限,如果您需要更多个元素,那么可以使用集合而不是元组。 对于每个TupleN类型,其中上限为1 <= N <= 22,Scala定义了许多元素访问方法。给定以下定义 -
val t = (4,3,2,1)
要访问元组t的元素,可以使用t._1方法访问第一个元素,t._2方法访问第二个元素,依此类推。 例如,以下表达式计算t的所有元素的总和 -
val sum = t._1 + t._2 + t._3 + t._4
可以使用Tuple以及采用List [Double]来编写一个方法,并返回在三元组元组Tuple3 [Int,Double,Double]中返回的计数,总和和平方和。它们也可用于将数据值列表作为并发编程中的参与者之间的消息传递。
请尝试以下示例程序。 它显示了如何使用元组。
object Demo {
def main(args: Array[String]) {
val t = (4,3,2,1)
val sum = t._1 + t._2 + t._3 + t._4
println( "Sum of elements: " + sum )
}
}
将上述程序保存在源文件:Demo.scala中,使用以下命令编译和执行此程序。
D:\>scalac Demo.scala
D:\>scala Demo
Sum of elements: 10
迭代元组
可以使用Tuple.productIterator()方法遍历元组的所有元素。
尝试以下示例程序来遍历元组。
示例
object Demo {
def main(args: Array[String]) {
val t = (4,3,2,1)
t.productIterator.foreach{ i =>println("Value = " + i )}
}
}
将上述程序保存在源文件:Demo.scala中,使用以下命令编译和执行此程序。
D:\>scalac Demo.scala
D:\>scala Demo
Value = 4
Value = 3
Value = 2
Value = 1
转换为字符串
可以使用Tuple.toString()方法将元组的所有元素连接成字符串。尝试以下示例程序转换为String。
以下是将元组转换为字符串的例子 -
object Demo {
def main(args: Array[String]) {
val t = new Tuple3(1, "hello", Console)
println("Concatenated String: " + t.toString() )
}
}
将上述程序保存在源文件:Demo.scala中,使用以下命令编译和执行此程序。
D:\>scalac Demo.scala
D:\>scala Demo
Concatenated String: (1,hello,scala.Console$@281acd47)
交换元素
可以使用Tuple.swap方法交换Tuple2中的元素。
尝试以下示例程序来交换元素。
object Demo {
def main(args: Array[String]) {
val t = new Tuple2("Scala", "hello")
println("Swapped Tuple: " + t.swap )
}
}
将上述程序保存在源文件:Demo.scala中,使用以下命令编译和执行此程序。
D:\>scalac Demo.scala
D:\>scala Demo
Swapped tuple: (hello,Scala)
Scala选项
Scala Option[T]是由给定类型的零或一个元素的一种容器。Option[T]可以是 Some [T]或None对象,它代表缺少的值。 例如,如果已找到与给定键对应的值,则Scala的Map的get方法会生成Some(value),如果在Map中未定义给定的键,则将返回None。
Option类型在Scala程序中经常使用,可以将其与Java中可用的null值进行比较,表示null值。 例如,java.util.HashMap的get方法返回存储在HashMap中的值,如果没有找到值,则返回null。
假设我们有一种基于主键从数据库中检索记录的方法。
def findPerson(key: Int): Option[Person]
如果找到记录,该方法将返回Some [Person],如果没有找到该记录,则返回None。下面来看看看以下程序代码 -
示例
object Demo {
def main(args: Array[String]) {
val capitals = Map("France" -> "Paris", "Japan" -> "Tokyo")
println("capitals.get( \"France\" ) : " + capitals.get( "France" ))
println("capitals.get( \"India\" ) : " + capitals.get( "India" ))
}
}
将上述程序保存在源文件:Demo.scala中,使用以下命令编译和执行此程序。
D:\>scalac Demo.scala
D:\>scala Demo
capitals.get( "France" ) : Some(Paris)
capitals.get( "India" ) : None
将可选值分开的最常见方法是通过模式匹配。例如尝试以下程序 -
object Demo {
def main(args: Array[String]) {
val capitals = Map("France" -> "Paris", "Japan" -> "Tokyo")
println("show(capitals.get( \"Japan\")) : " + show(capitals.get( "Japan")) )
println("show(capitals.get( \"India\")) : " + show(capitals.get( "India")) )
}
def show(x: Option[String]) = x match {
case Some(s) => s
case None => "?"
}
}
将上述程序保存在源文件:Demo.scala中,使用以下命令编译和执行此程序。
D:\>scalac Demo.scala
D:\>scala Demo
show(capitals.get( "Japan")) : Tokyo
show(capitals.get( "India")) : ?
使用getOrElse()方法
以下是示例程序,显示如何在没有值的情况下使用getOrElse()方法来访问值或默认值。
object Demo {
def main(args: Array[String]) {
val a:Option[Int] = Some(5)
val b:Option[Int] = None
println("a.getOrElse(0): " + a.getOrElse(0) )
println("b.getOrElse(10): " + b.getOrElse(10) )
}
}
将上述程序保存在源文件:Demo.scala中,使用以下命令编译和执行此程序。
D:\>scalac Demo.scala
D:\>scala Demo
a.getOrElse(0): 5
b.getOrElse(10): 10
使用isEmpty()方法
以下是显示如何使用isEmpty()方法检查该选项是否为None的示例程序。
object Demo {
def main(args: Array[String]) {
val a:Option[Int] = Some(5)
val b:Option[Int] = None
println("a.isEmpty: " + a.isEmpty )
println("b.isEmpty: " + b.isEmpty )
}
}
将上述程序保存在源文件:Demo.scala中,使用以下命令编译和执行此程序。
D:\>scalac Demo.scala
D:\>scala Demo
a.isEmpty: false
b.isEmpty: true
Scala迭代器
迭代器不是集合,而是一种逐个访问集合元素的方法。 下一个迭代器的两个基本操作是hasNext。 对it.next()方法的调用将返回迭代器的下一个元素,并提高迭代器的状态。可以使用Iterator的it.hasNext方法判断是否还有更多元素返回。
迭代器返回的所有元素最直接的方法是使用while循环。让我们参考以下示例程序 -
示例
object Demo {
def main(args: Array[String]) {
val it = Iterator("a", "number", "of", "words")
while (it.hasNext){
println(it.next())
}
}
}
将上述程序保存在源文件:Demo.scala中,使用以下命令编译和执行此程序。
D:\>scalac Demo.scala
D:\>scala Demo
a
number
of
words
查找最小和最大值元素
可以使用it.min和it.max方法从迭代器中找出最小值和最大值元素。 在这里,我们使用ita和itb执行两个不同的操作,因为迭代器只能遍历一次。以下是示例程序。
object Demo {
def main(args: Array[String]) {
val ita = Iterator(20,40,2,50,69, 90)
val itb = Iterator(20,40,2,50,69, 90)
println("Maximum valued element " + ita.max )
println("Minimum valued element " + itb.min )
}
}
将上述程序保存在源文件:Demo.scala中,使用以下命令编译和执行此程序。
D:\>scalac Demo.scala
D:\>scala Demo
Maximum valued element 90
Minimum valued element 2
查找迭代器的长度
可以使用it.size或it.length方法来查找迭代器中可用的元素数量。在这里,我们使用ita和itb执行两个不同的操作,因为迭代器只能遍历一次。 以下是示例程序的代码 -
object Demo {
def main(args: Array[String]) {
val ita = Iterator(20,40,2,50,69, 90)
val itb = Iterator(20,40,2,50,69, 90)
println("Value of ita.size : " + ita.size )
println("Value of itb.length : " + itb.length )
}
}
将上述程序保存在源文件:Demo.scala中,使用以下命令编译和执行此程序。
D:\>scalac Demo.scala
D:\>scala Demo
Value of ita.size : 6
Value of itb.length : 6
Spark记录-Scala集合的更多相关文章
- Spark记录-Scala程序例子(函数/List/match/option/泛型/隐式转换)
object func { def main(args:Array[String]):Unit={ //函数赋值给变量时, 必须在函数后面加上空格和下划线. def sayHello(name: St ...
- Spark记录-Scala数组/List/Map/Set
import Array._ import scala.collection.mutable.Set object DataStructure { def main(args:Array[String ...
- Spark记录-Scala语法基础
参考:http://docs.scala-lang.org/cheatsheets/index.html.http://docs.scala-lang.org/.http://www.scala-la ...
- Spark记录-Scala语句(运算符-if-for-while-try-模式匹配)
Scala条件运算符 Scala条件运算符在下表中列出. 运算符 操作 描述 && 与 运算符左侧和右侧的值为true.仅当左侧为真时,右侧才被计算. || 或 左侧或右侧的至少一个值 ...
- Spark记录-scala快速入门
1.hello world程序 object HelloWorld { def main(args: Array[String]) { println("Hello,World!" ...
- Spark记录-Scala数组
Scala提供了一种数据结构叫作数组,数组是一种存储了相同类型元素的固定大小顺序集合.数组用于存储数据集合,但将数组视为相同类型变量的集合通常更为有用. 可以声明一个数组变量,例如:numbers,使 ...
- Spark记录-Scala循环语句
Scala while循环语句 当给定条件为真时,while循环重复一个语句或一组语句.它在执行循环体之前测试条件状态. 只要给定的条件为真,while循环语句重复执行目标语句. object Dem ...
- Spark记录-Scala变量/访问修饰符/运算符
变量是保存存储值的内存位置的名称.这意味着当创建变量时,可以在内存中保留一些空间. 根据变量的数据类型,编译器分配内存并决定可以存储在预留内存中的内容.因此,通过为变量分配不同的数据类型,可以在这些变 ...
- Spark记录-Scala基础语法
如果您熟悉Java语言语法和编程,那么学习Scala将会很容易.Scala和Java之间最大的句法差异在于行结束字符的分号(;) 是可选的. 当编写Scala程序时,它可以被定义为通过调用彼此的方法进 ...
随机推荐
- HTML-JS 循环 函数 递归
[循环结构的执行步骤] 1.声明循环变量 2.判断循环条件 3.执行循环体操作 4.更新循环变量 然后,循环执行2-4,直到条件不成立时,跳出循环. while循环()中的表达式,运算结果可以是各种类 ...
- vuex实践之路——笔记本应用(二)
上一篇我们简单介绍了vuex在此项目中的作用. 这次来理一下项目的整体思路. main.js上次看过了,首先看App.vue文件 我们引入了Toolbar.vue,NodeList.vue,Edito ...
- PHP学习 函数 function
参数默认值function drink($kind ='tea'){echo 'would you please a cup'.$kind.'<br>';} drink();drink(' ...
- C++ 继承和派生介绍
继承(inheritance)是软件重用的一种方式,程序员通过继承可以吸收已有类的数据和行为来创建新类,并可以添加新的数据和行为来增强类的功能.创建新类时,并不需要创建全新的数据和成员函数,我们可以指 ...
- Daily Scrum NO.5
工作概况 符美潇 昨日完成的工作 1.Daily Scrum.日常会议及日常工作的分配和查收. 2.变更集461代码签入,主要与视频链接爬取有关. 今日工作 1.Daily Scrum.日常会议及日常 ...
- 20135202闫佳歆--week5 课本18章学习笔记
第十八章 调试 内核级开发的调试工作远比用户级开发艰难的多. 一.准备开始 准备工作需要的是: 一个bug 一个藏匿bug的内核版本 相关内核代码的知识和运气 在这一章里,调试的主要思想是让bug重现 ...
- Leetcode题库——36.有效的数独
@author: ZZQ @software: PyCharm @file: leetcode36_isValidSudoku.py @time: 2018/11/19 19:27 要求:判断一个 9 ...
- 第八周PSP(11.5--11.9)
2016.11.5 2016.11.6 2016.11.7 2016.11.8 2016.11.9
- mysql 列转行处理
CREATE TABLE `table1` ( `id` ) DEFAULT NULL, `name` ) CHARACTER SET utf8 DEFAULT NULL ) ENGINE=MyISA ...
- require.js text 插件使用
相比于使用script构建DOM结构,使用HTML标签来构建html是一个很好的方式.然而, 并没有很好的方式可以在js文件中嵌入 HTML .最好的方式是使用 HTML字符串, 但这很难管理,尤其实 ...