目录
一、Scala简介
二、Scala变量(var)与常量(val)
三、Scala数据类型
四、字符串插值
五、条件语句if...else...
六、for循环、中断、过滤与yield
小实验:打印加法
七、数组
(一)创建数组
(二)字符串集合相关方法
(三)数值类型集合相关方法
1.++
2.++:
3.+: 与:+
4./:与:\
5.addString
6.andThen(表达式)
7.par.aggregate
8.apply(索引值)取数组中的元素
9.canEqual(that:Any)
10.charAt()
11.clone()克隆
12.偏函数partialFunction[泛型,泛型]
13.collectFirst(偏函数)
14.combinations()
15.contains()与containsSlice()
16.copyToArray()
17.copyToBuffer()
18.corresponds
19.count()统计符合条件的元素个数
20.deep(索引值)
21.diff()求差集
22.drop(n)删除前n个元素
23.dropRight()从右删除n个元素
24.dropWhile()满足条件删除
25.distinct
26.endsWith()
27.exists(表达式)
28.filter(表达式)
29.filterNot(表达式)
30.find(表达式)
31.flatMap
32.flatten
33.fold(foldLeft)相当于 /:
34.foldRight相当于:\
35.forall(表达式)
36.foreach
37.getClass
38.groupBy()
39.grouped(数量)
40.hasDefiniteSize
41.head
42.headOption
43.indexOf()
44.indexOfSlice
45.indexWhere(表达式)
46.indices
47.init
48.inits
49.intersect
50.isDefinedAt(索引值)
51.isEmpty
52.isTraversableAgain
53.iterator
54.last
55.lastIndexOf()
56.lastIndexOfSlice
57.lastIndexWhere
58.lastOption
59.lengthCompare(Int)
60.lift(Int)
61.map(表达式)
62.max
63.maxBy(表达式)
64.min
65.minBy(表达式)
66.mkString()
67.nonEmpty
68.padTo
69.par
70.partition(表达式)
71.patch(from: Int,patch: scala.collection.GenSeq[B],replaced: Int)
72.permutations
73.prefixLength(表达式)
74.product
75.reduce
76.reduceLeft与reduceRight
77.reduceLeftOption与reduceRightOption
78.reverse
79.reverseIterator
80.reverseMap(集合操作的表达式)
81.runWith
82.sameElements
83.scan、scanLeft与scanRight
84.segmentLength(p: Int => Boolean,from: Int)
85.seq
86.size
87.slice
88.sliding
89.sortBy(表达式)
90.sortWith
91.sorted
92.span
93.splitAt
94.startsWith
95.stringPrefix
96.sum
97.tail
98.tails
99.take(Int)
100.takeRight(Int)
101.takeWhile
102.to
103.toArray
104.toBuffer
105.toIndexedSeq
106.toIterable与toIterator
107.toList
108.toMap
109.toSeq
110.toStream
111.toTraversable
112.toVector
113.transform
114.union
115.unzip
116.unzip3
117.update
118.updated(要修改的索引,要修改的元素)
119.view(切片开始元素位置,切片结束元素位置)
120.withFilter
121.zip
122.zipAll
123.zipWithIndex
Scala源自Java,构建在JVM之上,与Java兼容、互通。
Scala的优势:
1.多范式编程:
(1)面向对象编程:
每个值都是对象;
对象的数据类型和行为由类(Class)和特征(Trait,类似于interface)描述;
利用特征实现混入式多重继承。
(2)函数式编程:
每个函数都是一个值;
支持高阶函数、柯里化(currying)、样例类(case class)及模式匹配......
2.Scala是静态语言,表达能力强,代码精简
3.Spark采用Scala语言设计,提供的API更加优雅,基于JVM的语言更融入Hadoop生态圈。
4.扩展性:隐式类、字符串差值
变量:
赋值后可以改变,生命周期中可以被多次赋值。
var 变量名称:类型=xxx
一般无需显示指定类型,Scala编译器会自动推断出类型
// 下面的方式声明变量才不会报错 var name = "zhangsan" name="lisi" println(name) // lisi
常量:
赋值后不可变,类似于Java中的final变量
val 常量名称:类型=xxx
Scala与Java有相同的数据类型,但是Scala的数据类型首字母全部大写
Byte、Short、Int、Long、Float、Double、Char、Boolean、String
1)Scala中一切数据都是对象,都是Any的子类;
2)Scala中数据类型分为两大类:数值类型(AnyVal)、引用类型(AnyRef),不管是值类型还是引用类型都是对象;
3)Scala数据类型仍然遵守,低精度的值类型向高精度值类型,自动转换(隐式转换);
4)Scala中的StringOps是对Java中的String增强;
5)Unit:对应Java中的void,用于方法返回值的位置,表示方法没有返回值。Unit是 一个数据类型,只有一个对象就是()。Void不是数据类型,只是一个关键字;
6)Null是一个类型,只有一个对 象就 是null。它是所有引用类型(AnyRef)的子类;
7)Nothing,是所有数据类型的子类,主要用在一个函数没有明确返回值时使用,因为这样可以把抛出的返回值,返回给任何的变量或者函数。
s插值器:允许将变量引用、表达式直接插入字面字符中
// s插值器val name="xiaoming" println(s"Hello,${name}") // Hello,xiaoming println(s"1+1=${1+1}") // 1+1=2+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++var name = "张三丰" var age = 80 println(name+"是武当掌门,年龄"+age+"岁") // 张三丰是武当掌门,年龄80岁// 等同于 println(s"${name}是武当掌门,年龄${age}岁") // 张三丰是武当掌门,年龄80岁// 也可以去掉{},但是变量后面必须有空格 println(s"$name 是武当掌门,年龄$age 岁") // 张三丰 是武当掌门,年龄80 岁println(s"${name+age}是武当掌门,年龄$age 岁") // 张三丰80是武当掌门,年龄80 岁
f插值器:
// f插值器 val height = 1.9d val name = "xiaozhang" println(f"$name%s is $height%2.2f meters tall") // %s表示字符串,%2.2f表示整数位数为2,小数位数为2的浮点型数据 // xiaozhang is 1.90 meters tall
// if...else...可以简写成{}var num = 100;var y = {num + 1;}println(y) // 101var x = {num + 4println("hello")}println(x)/** hello() // 空元组* */
println(1 until 10)// Range(1, 2, 3, 4, 5, 6, 7, 8, 9)println(1 to 10)// Range(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)println(1.to(5))// Range(1, 2, 3, 4, 5)
// for循环
for (i:Int <- 1 to 10){print(i+",")}
// 1,2,3,4,5,6,7,8,9,10,import scala.util.control.Breaks._
// break语句
for (i:Int <- 1 to 10){if(i==6){break;}println(i)
}// for 循环过滤
for (i: Int <- 1 to 10; if i % 2 == 0) {println(i)}for (i: Int <- 1 to 10; if i % 2 == 0; if i <= 7) {println(i)}// yield 将结果赋值到集合中var arr = for (i: Int <- 1 to 10; if i % 2 == 0; if i < 8) yield iprintln(arr) // Vector(2, 4, 6)
var num = 6 for (i:Int <- 0 to num ){println(s"${i}+${num-i}=${num}")}
// 数组创建方式一
var arr1:Array[String]=new Array[String](3);
arr1(0)="zhangsan"
arr1(1)="lisi"
arr1(3)="wangwu"// 数组创建方式二
var arr2=Array("zhangsan","lisi","wangwu")// 数组创建方式三:区间数组
var arr3=Array.range(1,10,2)
scala> arr.
!= asInstanceOf drop foldRight inits maxBy reduceLeft slice toArray unzip3
## canEqual dropRight forall intersect min reduceLeftOption sliding toBuffer update
+ clone dropWhile foreach isDefinedAt minBy reduceOption sortBy toIndexedSeq updated
++ collect elemManifest formatted isEmpty mkString reduceRight sortWith toIterable view
++: collectFirst elemTag genericBuilder isInstanceOf ne reduceRightOption sorted toIterator wait
+: combinations endsWith getClass isTraversableAgain nonEmpty repr span toList withFilter
-> companion ensuring groupBy iterator notify reverse splitAt toMap zip
/: compose eq grouped last notifyAll reverseIterator startsWith toSeq zipAll
:+ contains equals hasDefiniteSize lastIndexOf orElse reverseMap stringPrefix toSet zipWithIndex
:\ containsSlice exists hashCode lastIndexOfSlice padTo runWith sum toStream →
== copyToArray filter head lastIndexWhere par sameElements synchronized toString
addString copyToBuffer filterNot headOption lastOption partition scan tail toTraversable
aggregate corresponds find indexOf length patch scanLeft tails toVector
andThen count flatMap indexOfSlice lengthCompare permutations scanRight take transform
apply deep flatten indexWhere lift prefixLength segmentLength takeRight transpose
applyOrElse diff fold indices map product seq takeWhile union
array distinct foldLeft init max reduce size to unzip
++ collectFirst dropWhile genericBuilder isTraversableAgain mkString reduceRightOption sortBy toBuffer unzip3
++: combinations elemManifest groupBy iterator nonEmpty repr sortWith toIndexedSeq update
+: companion elemTag grouped last orElse reverse sorted toIterable updated
/: compose endsWith hasDefiniteSize lastIndexOf padTo reverseIterator span toIterator view
:+ contains exists head lastIndexOfSlice par reverseMap splitAt toList withFilter
:\ containsSlice filter headOption lastIndexWhere partition runWith startsWith toMap zip
addString copyToArray filterNot indexOf lastOption patch sameElements stringPrefix toSeq zipAll
aggregate copyToBuffer find indexOfSlice length permutations scan sum toSet zipWithIndex
andThen corresponds flatMap indexWhere lengthCompare prefixLength scanLeft tail toStream
apply count flatten indices lift product scanRight tails toTraversable
applyOrElse deep fold init map reduce segmentLength take toVector
array diff foldLeft inits max reduceLeft seq takeRight transform
canEqual distinct foldRight intersect maxBy reduceLeftOption size takeWhile transpose
clone drop forall isDefinedAt min reduceOption slice to union
collect dropRight foreach isEmpty minBy reduceRight sliding toArray unzip
# 定义一个集合,scala会自动检测是String类型
scala> var arr = Array("abv","cd","123")
arr: Array[String] = Array(abv, cd, 123)# 定义一个集合,scala会自动检测是Int类型
scala> var arr2 = Array(1,2,3,45)
arr2: Array[Int] = Array(1, 2, 3, 45)scala> var arr3 = Array(5,6,7)
arr3: Array[Int] = Array(5, 6, 7)
合并集合并返回一个新数组,新数组包含两个集合对象的内容。
如果合并的集合类型一样,新数组的类型也相同;如果合并的集合类型不一样,新数组的类型是Any。
根据++的顺序进行从左往右的拼接
# 两个不同类型的数组++时
scala> arr ++ arr2
res3: Array[Any] = Array(abv, cd, 123, 1, 2, 3, 45)# 两个相同类型的数组++时
scala> arr2 ++ arr3
res4: Array[Int] = Array(1, 2, 3, 45, 5, 6, 7)scala> arr2 ++ arr
res5: Array[Any] = Array(1, 2, 3, 45, abv, cd, 123)
scala> arr4
res2: List[Int] = List(1, 2)scala> arr5
res3: scala.collection.mutable.LinkedList[Int] = LinkedList(8, 9)# 谁在:的右侧,数组相加后就是右侧的数据类型
scala> arr4 ++: arr5
warning: there was one deprecation warning; re-run with -deprecation for details
res4: scala.collection.mutable.LinkedList[Int] = LinkedList(1, 2, 8, 9)scala> arr5 ++: arr4
res5: List[Int] = List(8, 9, 1, 2)
scala> var arr = Array(1,2,3)
arr: Array[Int] = Array(1, 2, 3)# 将元素加在集合的头部
scala> 10 +: arr
res0: Array[Int] = Array(10, 1, 2, 3)# 将元素加在集合的尾部
scala> arr :+ 10
res1: Array[Int] = Array(1, 2, 3, 10)# 合并的元素与原来的集合不一致返回的新数组就是Any类型
scala> arr :+ "abc"
res2: Array[Any] = Array(1, 2, 3, abc)
左子树与右子数
初始值与数组第一个元素相加(10+1=11),结果与数组第二个元素相加(11+2=13),相加结果再与第三个元素相加(13+3=16)
scala> var arr = Array(1,2,3)# 10相当于初始值
scala> (10 /: arr)(_+_)
res4: Int = 16scala> (arr :\ 10)(_+_)
res3: Int = 16
def addString(b: StringBuilder): StringBuilder
def addString(b: StringBuilder,sep: String): StringBuilder
def addString(b: StringBuilder,start: String,sep: String,end: String): StringBuilder
# StringBuilder有效扩展可变字符串
scala> var b = new StringBuilder()
b: StringBuilder =scala> var arr = Array(1,2,3)
arr: Array[Int] = Array(1, 2, 3)# 将arr集合中的内容变为字符串,存入对象b中
scala> arr.addString(b)
res7: StringBuilder = 123# 再执行一次字符串变长
scala> arr.addString(b)
res9: StringBuilder = 123123scala> arr
res278: Array[Int] = Array(1, 2, 3, 16, 1, 2)# 将数组中的元素以逗号分隔连成字符串,追加到字符串空间中
scala> arr.addString(new StringBuilder(),",")
res281: StringBuilder = 1,2,3,16,1,2# 以hello开头,逗号分割,scala结尾,连成字符串,追加到字符串空间中
scala> arr.addString(new StringBuilder(),"hello",",","scala")
res285: StringBuilder = hello1,2,3,16,1,2scala
使用范式: def andThen[C](k: Any => C): PartialFunction[Int,C]
使用说明:根据k方法生成偏函数,Int为索引,C为k方法执行的结果类型
scala> arr
res158: Array[Int] = Array(1, 2, 33, 7, 17, 18, 18)scala> arr.andThen(_>=10)
res159: PartialFunction[Int,Boolean] = scala> res159(4)
res161: Boolean = truescala> res159(0)
res162: Boolean = falsescala> arr.andThen((x)=>(x+1)%2==0)
res163: PartialFunction[Int,Boolean] = scala> res163(0)
res164: Boolean = true
根据数组的个数和计算机的核数,将每一个值都做为一个线程
par有线程并发问题,线程不安全,所以par尽量少用
scala> arr
res9: Array[Int] = Array(1, 2, 3)# 定义函数,返回值为Int
scala> def one(p1:Int,p2:Int):Int={| println(s"one function:${p1},${p2}");| p1+p2;| }
one: (p1: Int, p2: Int)Int# 定义函数:返回值不定义
scala> def two(p1:Int,p2:Int)={| println(s"two function:${p1},${p2}");| p1+p2;| }
two: (p1: Int, p2: Int)Intscala> arr.par.aggregate(5)(one,two)
one function:5,1
one function:5,2
one function:5,3
two function:7,8
two function:6,15
res10: Int = 21
# 初始值5与集合中的每个数都相加,5+1=6,5+2=7,5+3=8
# 得数再进行线程抢资源相加,7和8先抢到,7+8=15,15随后与6相加=21scala> arr.par.aggregate(5)(_+_,_+_)
res12: Int = 21-------------------------------------------------------------------------------------------
# 上述代码可以简化# 由于多线程不安全的关系,可能1还没开始和5进行相加,2和3已经与5加好了
# 5+2=7,5+3=8,7+8=15,15+1=16
scala> arr.par.aggregate(5)(_+_,_+_)
res14: Int = 16scala> arr.par.aggregate(5)(_+_,_+_)
res15: Int = 21--------------------------------------------------------------------------------------
scala> arr.par.aggregate(5)((p1,p2)=>{p1+p2},(p1,p2)=>p1+p2)
res21: Int = 16scala> arr.par.aggregate(5)((p1,p2)=>{println(s"${p1},${p2}");p1+p2},(p1,p2)=>p1+p2)
5,1
5,3
5,2
res24: Int = 21--------------------------------------------------------------------------------------scala> a.par.aggregate(0)((x,y)=>{println("left",x,y);x+y},(x,y)=>{println("right",x,y);x+y})
(left,0,3)
(left,0,6)
(left,0,7)
(right,3,6)
(left,0,1)
(right,1,7)
(right,9,8)
res24: Int = 17
scala> var arr = Array(1,2,3)scala> arr.apply(2)
res18: Int = 3scala> arr(2)
res19: Int = 3scala> arr(3)
java.lang.ArrayIndexOutOfBoundsException: 3... 32 elided
判断两个对象是否可以比较,返回boolean,结果永远为true
scala> arr.canEqual(1)
res22: Boolean = truescala> arr.canEqual("aa")
res23: Boolean = truescala> arr.canEqual(None)
res24: Boolean = true
scala> var arr1 = Array('a','b','c')
arr1: Array[Char] = Array(a, b, c)scala> arr1.charAt(2)
res26: Char = c
# 等同于
scala> arr1(2)
res27: Char = cscala> var str = "abcdef"
str: String = abcdefscala> str.charAt(2)
res30: Char = cscala> char.collect({case 'a' => 'A'})
res28: Array[Char] = Array(A)scala> char.collect({case 'a' => 'A' case x=>x})
res29: Array[Char] = Array(A, b, c)
scala> arr
res26: Array[Int] = Array(1, 2, 3)scala> def abc(sz:Array[Int])={| sz(1)=100;| }
abc: (sz: Array[Int])Unitscala> abc(arr)scala> arr
res29: Array[Int] = Array(1, 100, 3)-------------------------------------------------------------------------------------------scala> arr.clone()
res30: Array[Int] = Array(1, 100, 3)scala> def abc(sz:Array[Int])={| sz(1)=10;| }
abc: (sz: Array[Int])Unit# 传参:res30作为实参传递给函数abc的形参sz
scala> abc(res30)# 原数组未变
scala> arr
res33: Array[Int] = Array(1, 100, 3)scala> res30
res35: Array[Int] = Array(1, 10, 3)
scala> char.collect({case 'a' => 'A'})
res28: Array[Char] = Array(A)scala> char.collect({case 'a' => 'A' case x=>x})
res29: Array[Char] = Array(A, b, c)scala> arr :+ 124
res44: Array[Int] = Array(1, 100, 3, 124)# 设置偏函数,将数组中偶数的值+5
scala> def pfun:PartialFunction[Int,Int]={| case x if(x%2==0) => x+5 # case是模式守卫| }
pfun: PartialFunction[Int,Int]# 得出的结果放在collect中
scala> res44.collect(pfun)
res46: Array[Int] = Array(105, 129)# 匿名函数
# 函数写法也可以简化(函数){函数内容}
scala> res44.collect{case x if(x%2==0)=>x+5}
res47: Array[Int] = Array(105, 129)scala> res44.collect({case x if(x%2==0)=>x+5})
res48: Array[Int] = Array(105, 129)scala> var info = Array("male","男","1","female","女","0")
info: Array[String] = Array(male, 男, 1, female, 女, 0)scala> info.collect({case "男"=>"male" case "女"=>"female" case "1"=>"male" case "0"=>"female" case x=>x})
res32: Array[String] = Array(male, male, male, female, female, female)scala> info
res33: Array[String] = Array(male, 男, 1, female, 女, 0)scala> var arr = Array(1,'a',"b")
arr: Array[Any] = Array(1, a, b)scala> arr.collectFirst({case x:Int => x*100})
res34: Option[Int] = Some(100)scala> var arr = Array(1,3,'a',"b")
arr: Array[Any] = Array(1, 3, a, b)# 仅找到第一个符合条件的值就停止
scala> arr.collectFirst({case x:Int => x*100})
res35: Option[Int] = Some(100)scala> arr.collect({case x:Int => x*100})
res36: Array[Int] = Array(100, 300)
在序列中查找第一个符合偏函数定义的元素,并执行偏函数计算
scala> res44.collectFirst({case x if(x%2==0)=>x+5})
res49: Option[Int] = Some(105)
# some表示有内容,只能放一个元素,所以.get后面不接参数
# 尽管结果有多个,但是该函数找到一个符合的值就结束scala> res44.collectFirst({case x if(x%2==0)=>x+5}).get
res50: Int = 105scala> res44.collectFirst({case x if(x>200)=>x+5})
res52: Option[Int] = None # None表示没有内容# 当没有一个条件符合时,就找不到
scala> res44.collectFirst({case x if(x>200)=>x+5}).get
java.util.NoSuchElementException: None.getat scala.None$.get(Option.scala:347)at scala.None$.get(Option.scala:345)... 32 elidedscala> var arr = Array(1,'a',"b")
arr: Array[Any] = Array(1, a, b)scala> arr.collectFirst({case x:Int => x*100})
res34: Option[Int] = Some(100)scala> var arr = Array(1,3,'a',"b")
arr: Array[Any] = Array(1, 3, a, b)# 仅找到第一个符合条件的值就停止
scala> arr.collectFirst({case x:Int => x*100})
res35: Option[Int] = Some(100)scala> arr.collect({case x:Int => x*100})
res36: Array[Int] = Array(100, 300)scala> arr.collect({case x:Int => x*100 case x=>x})
res37: Array[Any] = Array(100, 300, a, b)
根据集合a元素组合(无重复),返回长度为n的集合的迭代器,和排列permutations联合记忆
scala> arr.combinations(2)
res53: Iterator[Array[Int]] = non-empty iterator# 遍历迭代器
scala> arr.combinations(2).foreach(println)
[I@32043bfe
[I@6757b82e
[I@70ef835c # 上述地址值转为值遍历输出
scala> arr.combinations(2).foreach(x=>println(x.mkString(",")))
1,100
1,3
100,3scala> res53.foreach(x=>println(x.mkString(",")))
1,100
1,3
100,3scala> res53.foreach(x=>println(x.mkString(",")))
# 迭代器执行第二次,指针走完,没有值,迭代器性能比数组快,迭代器是java所有跟接口的父接口scala> arr.combinations(2)
res38: Iterator[Array[Any]] = non-empty iteratorscala> res38.foreach((x)=>println(x))
[Ljava.lang.Object;@124eb013
[Ljava.lang.Object;@624697e8
[Ljava.lang.Object;@3f62d3f6
[Ljava.lang.Object;@1ca7d9c5
[Ljava.lang.Object;@7b8e3c6a
[Ljava.lang.Object;@2d210d24scala> arr.combinations(2)
res40: Iterator[Array[Any]] = non-empty iteratorscala> res40.foreach((x)=>println(x.mkString("(",",",")")))
(1,3)
(1,a)
(1,b)
(3,a)
(3,b)
(a,b)
是否包含元素或序列
scala> arr.contains(4)
res62: Boolean = falsescala> arr.contains(100)
res63: Boolean = truescala> arr
res64: Array[Int] = Array(1, 100, 3)# 是否包含一个序列
scala> arr.containsSlice(Seq(1,3))
res66: Boolean = falsescala> arr.containsSlice(Seq(100,3))
res67: Boolean = true# 大集合是否包含小集合,小集合的次序与大集合中的次序段一样
scala> arr.containsSlice(List(100,3))
res42: Boolean = truescala> arr.containsSlice(List(1,3))
res43: Boolean = false
此方法还有两个类似的方法
copyToArray(xs: Array[A], start: Int): Unit
copyToArray(xs: Array[A], start: Int, len: Int): Unit
scala> var arr3 = Array(0,0,0,0,0)
arr3: Array[Int] = Array(0, 0, 0, 0, 0)scala> arr.copyToArray(arr3,1,3)scala> arr3
res71: Array[Int] = Array(0, 1, 100, 3, 0)
# 可变集合包
scala> import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.ArrayBufferscala> var lst = ArrayBuffer()
lst: scala.collection.mutable.ArrayBuffer[Nothing] = ArrayBuffer()scala> val lst = new ArrayBuffer()
lst: scala.collection.mutable.ArrayBuffer[Nothing] = ArrayBuffer()scala> val lst = new ArrayBuffer[Int]()
lst: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer()scala> arr.copyToBuffer(lst)scala> lst
res73: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1, 100, 3)
判断两个序列长度以及对应位置元素是否符合某个条件。如果两个序列具有相同的元素数量并且p(x, y)=true,返回结果为true
下面代码检查a和b长度是否相等,并且a中元素是否小于b中对应位置的元素
scala> var arr1 = Array(1,2,3)
arr1: Array[Int] = Array(1, 2, 3)scala> arr
res74: Array[Int] = Array(1, 100, 3)# 比较两个数组,(arr <= arr1)
scala> arr.corresponds(arr1)(_<=_)
res75: Boolean = falsescala> arr.corresponds(arr1)(_>=_)
res76: Boolean = true# 当比较的两个数组长度不一样时,肯定是false
scala> (arr :+ 10).corresponds(arr1)(_>=_)
res78: Boolean = falsescala> (arr).corresponds((arr1 :+ 10))(_>=_)
res79: Boolean = false
scala> arr
res74: Array[Int] = Array(1, 100, 3)# 匿名函数
scala> arr.count(x=>x%2==0)
res82: Int = 1
根据数组元素的索引值获取元素
scala> arr
res143: Array[Int] = Array(1, 2, 33, 7, 17, 18, 18)scala> arr.deep(33)
java.lang.ArrayIndexOutOfBoundsException: 33at scala.collection.mutable.ArrayOps$ofInt$.apply$extension(ArrayOps.scala:241)at scala.collection.mutable.ArrayOps$ofInt.apply(ArrayOps.scala:234)at scala.collection.mutable.ArrayLike$$anon$1.apply(ArrayLike.scala:42)... 32 elidedscala> arr.deep(3)
res145: Any = 7
计算当前数组与另一个数组的不同。将当前数组中没有在另一个数组中出现的元素返回
scala> arr
res83: Array[Int] = Array(1, 100, 3)scala> arr1
res84: Array[Int] = Array(1, 2, 3)scala> arr.diff(arr1)
res85: Array[Int] = Array(100)
# SQL去重distinct、group by、窗口函数row number
scala> arr.drop(1)
res86: Array[Int] = Array(100, 3)
scala> arr.dropRight(1)
res87: Array[Int] = Array(1, 100)
去除当前数组中符合条件的元素,这个需要一个条件,就是从当前数组的第一个元素起,就要满足条件,直到碰到第一个不满足条件的元素结束(即使后面还有符合条件的元素),否则返回整个数组。
scala> arr.dropWhile(x=>x<100)
res88: Array[Int] = Array(100, 3)scala> ints
res50: Array[Int] = Array(5, 8, 66, 4)scala> ints.dropWhile({_<=8})
res52: Array[Int] = Array(66, 4)scala> ints2.dropWhile(_>=1)
res64: Array[Int] = Array()
scala> var ints = Array(1,2,3,3)
ints: Array[Int] = Array(1, 2, 3, 3)scala> ints.distinct
res53: Array[Int] = Array(1, 2, 3)
返回值Boolean,判断数组是否以某个集合为结尾
scala> arr.endsWith(List(100,3))
res89: Boolean = true
判断数组中的元素,是否匹配表达式的结果,有一个元素匹配表达式的结果就返回true
scala> arr
res130: Array[Int] = Array(1, 2, 33, 7, 17, 18, 18)scala> arr.exists(_>=1)
res129: Boolean = true
返回匹配表达式的结果,并生成一个新数组
scala> arr.filterdef filter(p: Int => Boolean): Array[Int]scala> arr
res130: Array[Int] = Array(1, 2, 33, 7, 17, 18, 18)scala> arr.filter(_>=18)
res135: Array[Int] = Array(33, 18, 18)
返回数组中不满足表达式的元素,并生成新数组
scala> arr.filterNot(x=>x%2==0)
res92: Array[Int] = Array(1, 3)scala> arr.filterNot(_>=18)
res137: Array[Int] = Array(1, 2, 7, 17)
返回数组中第一个满足表达式的元素,返回值类型Some或None
scala> arr.findoverride def find(p: Int => Boolean): Option[Int]scala> arr.find(x=>x%2==0)
res93: Option[Int] = Some(100)scala> arr.find(_>100)
res140: Option[Int] = None# lambda表达式:只用一次的变量,就用_来替代
scala> arr.find(_>1)
res94: Option[Int] = Some(100)scala> arr.find((x)=>{x>1})
res95: Option[Int] = Some(100)scala> def fc(k:Int)={| k>1| }
fc: (k: Int)Boolean# 也可以传入自定义函数
scala> arr.find(fc)
res96: Option[Int] = Some(100)
对当前序列的每个元素进行操作,结果放进新序列返回,相对于map是映射降一维
scala> ints
res74: Array[Int] = Array(1, 2, 3, 3)scala> ints.flatMap(x=>1 to x)
res75: Array[Int] = Array(1, 1, 2, 1, 2, 3, 1, 2, 3)scala> val arrays = Array(Array(1,2,3),Array(4,5,6),Array(7,8,9));
arrays: Array[Array[Int]] = Array(Array(1, 2, 3), Array(4, 5, 6), Array(7, 8, 9))scala> arrays.flatMap(x=>x)
res82: Array[Int] = Array(1, 2, 3, 4, 5, 6, 7, 8, 9)-------------------------------------------------------------------------------------------scala> val arrays = Array(Array(Array(11,12),Array(13,14)),Array(Array(15,16),Array(17,18)))scala> arrays.flatMap(x=>x)
res84: Array[Array[Int]] = Array(Array(11, 12), Array(13, 14), Array(15, 16), Array(17, 18))scala> arrays.flatMap(x=>x).flatMap(x=>x)
res85: Array[Int] = Array(11, 12, 13, 14, 15, 16, 17, 18)
数组降一维
scala> val arrays = Array(Array(Array(11,12),Array(13,14)),Array(Array(15,16),Array(17,18)))scala> arrays.flatten
res87: Array[Array[Int]] = Array(Array(11, 12), Array(13, 14), Array(15, 16), Array(17, 18))scala> arrays.flatten.flatten
res88: Array[Int] = Array(11, 12, 13, 14, 15, 16, 17, 18)
scala> ints.fold(100)((x,y)=>{println(x,y);(x*y)})
(100,1)
(100,2)
(200,3)
(600,3)
res91: Int = 1800scala> ints.foldLeft(100)((x,y)=>{println(x,y);(x*y)})
(100,1)
(100,2)
(200,3)
(600,3)
res92: Int = 1800
scala> ints.foldRight(100)((x,y)=>{println(x,y);(x*y)})
(3,100)
(3,300)
(2,900)
(1,1800)
res93: Int = 1800
数组中的所有元素是否满足表达式
scala> ints
res97: Array[Int] = Array(1, 2, 3, 3)scala> ints.forall(_>2)
res94: Boolean = falsescala> ints.forall(_>=1)
res96: Boolean = truescala> ints.forall((x)=>{x>2})
res98: Boolean = falsescala> ints.forall((x)=>{x>=1})
res99: Boolean = true
遍历输出数组中的元素
scala> arr.foreach(x=>println(x))
1
2
33
7
17
18
18scala> arr.foreach(x=>print(x))
12337171818scala> arr.foreach(x=>print(x+","))
1,2,33,7,17,18,18,scala> ints.foreach(println(_))
1
2
3
3
返回数组的类型
scala> arr
res180: Array[Int] = Array(1, 2, 33, 7, 17, 18, 18)scala> arr.getClass
res181: Class[_ <: Array[Int]] = class [I
scala> ints.groupBy((x)=>{if (x%2==0) {0} else {1}})
res105: scala.collection.immutable.Map[Int,Array[Int]] = Map(1 -> Array(1, 3, 3), 0 -> Array(2))scala> arr.groupBy((x)=> {if (x%2==0){"偶数"} else {"奇数"}})
res188: scala.collection.immutable.Map[String,Array[Int]] = Map(奇数 -> Array(1, 33, 7, 17), 偶数 -> Array(2, 18, 18))
将数组中的元素按照数量进行分组
# 每4个分为一组
scala> arr.grouped(4)
res192: Iterator[Array[Int]] = non-empty iteratorscala> res192.toArray
res194: Array[Array[Int]] = Array(Array(1, 2, 33, 7), Array(17, 18, 18))# 每3个分为一组
scala> arr.grouped(3)
res195: Iterator[Array[Int]] = non-empty iteratorscala> res195.toArray
res196: Array[Array[Int]] = Array(Array(1, 2, 33), Array(7, 17, 18), Array(18))
判断数组是否定义了长度
scala> arr.hasDefiniteSize
res197: Boolean = true
返回数组中第一个元素
scala> arr.head
res198: Int = 1scala> arr
res199: Array[Int] = Array(1, 2, 33, 7, 17, 18, 18)
返回头部对象
scala> arr.headOption
res200: Option[Int] = Some(1)
返回数组中指定元素第一次出现的下标
def indexOf[B >: Int](elem: B,from: Int): Int
def indexOf[B >: Int](elem: B): Int
scala> arr
res208: Array[Int] = Array(1, 5, 5, 6, 8, 9, 5)# 返回数组中元素5第一次出现的下标
scala> arr.indexOf(5)
res214: Int = 1# 返回从索引3开始,元素5第一次出现的下标
scala> arr.indexOf(5,3)
res215: Int = 6# 返回从索引3开始,元素8第一次出现的下标
scala> arr.indexOf(8,3)
res213: Int = 4
同上,返回数组第一次出现的下标
def indexOfSlice[B >: Int](that: scala.collection.GenSeq[B],from: Int): Int
def indexOfSlice[B >: Int](that: scala.collection.GenSeq[B]): Int
scala> arr.indexOfSlice(Array(9,5))
res218: Int = 5scala> arr
res219: Array[Int] = Array(1, 5, 5, 6, 8, 9, 5)scala> arr.indexOfSlice(Array(9,5),3)
res220: Int = 5
返回数组中满足表达式结果的,第一个元素的下标
scala> arr
res225: Array[Int] = Array(1, 5, 5, 6, 8, 9, 5)scala> arr.indexWhere(_%2==0)
res223: Int = 3
返回数组中所有元素的下标,返回值类型:Range
scala> arr.indices
res226: scala.collection.immutable.Range = Range(0, 1, 2, 3, 4, 5, 6)
去掉数组中最后一个元素,并返回新数组
scala> arr.init
res227: Array[Int] = Array(1, 5, 5, 6, 8, 9)
def inits: Iterator[Array[Int]]
将当前序列执行多次init操作,直到结果为空,则顺序返回序列的迭代器
scala> arr.inits.foreach(x=>println(x.mkString(",")))
1,5,5,6,8,9,5
1,5,5,6,8,9
1,5,5,6,8
1,5,5,6
1,5,5
1,5
1
返回两个数组的交集
scala> var arr1 = Array(1,2,5,5,6,6)
arr1: Array[Int] = Array(1, 2, 5, 5, 6, 6)scala> var arr2 = Array(1,2,7,4,9,6)
arr2: Array[Int] = Array(1, 2, 7, 4, 9, 6)scala> arr1.intersect(arr2)
res244: Array[Int] = Array(1, 2, 6)scala> arr2.intersect(arr1)
res245: Array[Int] = Array(1, 2, 6)
判断数组中是否存在指定索引
def isDefinedAt(idx: Int): Boolean
scala> var arr = Array(1,2,3)
arr: Array[Int] = Array(1, 2, 3)scala> arr.isDefinedAt(2)
res0: Boolean = truescala> arr.isDefinedAt(3)
res1: Boolean = false
判断数组是否为空
scala> arr.isEmpty
res2: Boolean = false
判断集合是否非迭代器,返回false则为迭代器
scala> arr
res4: Array[Int] = Array(1, 2, 3)scala> arr.isTraversableAgain
res3: Boolean = true
生成序列的迭代器,返回可迭代对象
scala> arr
res4: Array[Int] = Array(1, 2, 3)scala> arr.iterator.foreach(println(_))
1
2
3
取数组中最后一个元素
scala> arr
res4: Array[Int] = Array(1, 2, 3)scala> arr.last
res6: Int = 3
def lastIndexOf[B >: Int](elem: B,end: Int): Int
def lastIndexOf[B >: Int](elem: B): Int
返回序列中最后一个等于elem的元素的索引,可以指定结束下标end
scala> arr
res4: Array[Int] = Array(1, 2, 3)scala> arr.lastIndexOf(2)
res8: Int = 1# 下标1之前查找元素2
scala> arr.lastIndexOf(2,1)
res9: Int = 1# 下标1之前查找元素3
scala> arr.lastIndexOf(3,1)
res10: Int = -1# 下标3之前查找元素3
scala> arr.lastIndexOf(3,3)
res11: Int = 2
使用范式:lastIndexOfSlice[B >: Any](that: scala.collection.GenSeq[B],end: Int): Int
使用说明:判断当前序列是否存在指定序列,返回该序列最后一次出现的位置的首元素下标,可以指定最后检索的位置,如不指定end,则默认为最后一位def lastIndexOfSlice[B >: Int](that: scala.collection.GenSeq[B],end: Int): Int
def lastIndexOfSlice[B >: Int](that: scala.collection.GenSeq[B]): Int
scala> var arr = Array(1,2,3,4,1,2)
arr: Array[Int] = Array(1, 2, 3, 4, 1, 2)# 下标3之前集合最后一次出现的位置
scala> arr.lastIndexOfSlice(Array(1,2),3)
res17: Int = 0# 下标5之前集合最后一次出现的位置
scala> arr.lastIndexOfSlice(Array(1,2),5)
res18: Int = 4# 集合最后一次出现的位置
scala> arr.lastIndexOfSlice(Array(1,2))
res20: Int = 4
返回集合中满足表达式的最后一个元素的下标,可以指定最后检索的位置,如不指定end,则默认为最后一位
override def lastIndexWhere(p: Int => Boolean,end: Int): Int
def lastIndexWhere(p: Int => Boolean): Int
scala> arr
res22: Array[Int] = Array(1, 2, 3, 4, 1, 2)# 下标4之前,满足表达式的最后一个元素下标
scala> arr.lastIndexWhere(_%2==0,4)
res23: Int = 3# 满足表达式的最后一个元素下标
scala> arr.lastIndexWhere(_%2==0)
res24: Int = 5
返回数组中最后一个元素对象(some)
scala> arr.lastOption
res25: Option[Int] = Some(2)
返回数组长度与Int的差=arr.length-Int
scala> arr
res28: Array[Int] = Array(1, 2, 3, 4, 1, 2)# 集合长度6-给定的值6=0
scala> arr.lengthCompare(6)
res27: Int = 0# 6-2=4
scala> arr.lengthCompare(2)
res29: Int = 4# 6-8=-2
scala> arr.lengthCompare(8)
res32: Int = -2
给序列的索引,返回该索引处的Option类的值,如果越界会返回None
scala> arr
res33: Array[Int] = Array(1, 2, 3, 4, 1, 2)scala> arr.lift(2)
res38: Option[Int] = Some(3)scala> arr.lift(8)
res39: Option[Int] = None
对数组中的元素进行表达式操作,返回一个与原序列相同类型的序列
scala> arr.map(_*2)
res41: Array[Int] = Array(2, 4, 6, 8, 2, 4)scala> arr
res42: Array[Int] = Array(1, 2, 3, 4, 1, 2)------------------------------------------------------------------------------------------
scala> arr.map(_+"")
res3: Array[String] = Array(abv, cd, 123)# Int类型的数组使用map(_+"")转为String类型
scala> arr2.map(_+"")
res4: Array[String] = Array(1, 2, 3, 45)# Int类型的数组转为String类型与String类型的数组进行拼接,返回的新数组是String类型
scala> arr2.map(_+"") ++ arr
res5: Array[String] = Array(1, 2, 3, 45, abv, cd, 123)
返回数组中的最大值
scala> arr
res42: Array[Int] = Array(1, 2, 3, 4, 1, 2)scala> arr.max
res43: Int = 4scala> str
res44: Array[String] = Array(zhangsan, lisi, wangwu)scala> str.max
res45: String = zhangsan
返回数组中第一个满足表达式的元素,类似于find
scala> arr
res48: Array[Int] = Array(1, 2, 3, 4, 1, 2)scala> arr.maxBy(_%2==0)
res49: Int = 2scala> arr.maxBy(_>=4)
res50: Int = 4
返回数组的最小值
scala> arr
res54: Array[Int] = Array(1, 2, 3, 4, 1, 2)scala> arr.min
res52: Int = 1scala> str
res56: Array[String] = Array(zhangsan, lisi, wangwu)scala> str.min
res53: String = lisi
返回集合中第一个不符合表达式的元素
scala> arr
res54: Array[Int] = Array(1, 2, 3, 4, 1, 2)scala> arr.minBy(_%2==0)
res57: Int = 1
def mkString(sep: String): String
def mkString: String
def mkString(start: String,sep: String,end: String): String
# 将集合以字符串形式输出
scala> arr.mkString
res58: String = 123412# 集合以字符串输出时以,号分割
scala> arr.mkString(",")
res59: String = 1,2,3,4,1,2# 集合以字符串输出时,以hello为开头,以,号为分割,以world为结尾
scala> arr.mkString("hello",",","wolrd")
res62: String = hello1,2,3,4,1,2wolrd
判断数组是否非空
scala> arr.nonEmpty
res63: Boolean = true
在数组结尾处追加新元素,补齐长度len
# 用111来追加集合,使得集合长度为10
scala> arr.padTo(10,111)
res67: Array[Int] = Array(1, 2, 3, 4, 1, 2, 111, 111, 111, 111)scala> arr.padTo(10,"JAVA")
res68: Array[Any] = Array(1, 2, 3, 4, 1, 2, JAVA, JAVA, JAVA, JAVA)
返回并行序列,且每次返回的序列中各元素的次序不一定相同
scala> arr.par.foreach(println(_))
1
3
2
1
2
4scala> arr.par.foreach(println(_))
1
2
1
3
4
2scala> arr.par.foreach(println(_))
1
2
1
3
2
4
将数组按照表达式产生的结果拆分,满足条件放入一个数组,不满足条件的放入另一个数组
scala> arr
res75: Array[Int] = Array(1, 2, 3, 4, 1, 2)scala> arr.partition(_%3==0)
res77: (Array[Int], Array[Int]) = (Array(3),Array(1, 2, 4, 1, 2))
从下标值,替换序列B的值,replaced表示替换原数组中的元素个数
scala> arr
res79: Array[Int] = Array(1, 2, 3, 4, 1, 2)scala> arr.patch(1,Array(19,87),3)
res80: Array[Int] = Array(1, 19, 87, 1, 2)scala> arr.patch(1,Array(19,87),1)
res81: Array[Int] = Array(1, 19, 87, 3, 4, 1, 2)scala> arr.patch(1,Array(19,87),0)
res82: Array[Int] = Array(1, 19, 87, 2, 3, 4, 1, 2)
列出数组中所有元素所有排列方式,将当前序列的所有的排列可能结果组成作为一个迭代器(二维)返回
scala> var s = Array(1,2,3)
s: Array[Int] = Array(1, 2, 3)scala> s.permutations.toList
res86: List[Array[Int]] = List(Array(1, 2, 3), Array(1, 3, 2), Array(2, 1, 3), Array(2, 3, 1), Array(3, 1, 2), Array(3, 2, 1))
从头开始计数满足条件p的元素,碰到第一个不满足的则停止计数,返回计数值(Int)
scala> arr
res89: Array[Int] = Array(1, 2, 3, 4, 1, 2)scala> arr.prefixLength((x)=>(x+1)%2==0)
res91: Int = 1scala> var b = Array(3,5,8,12)
b: Array[Int] = Array(3, 5, 8, 12)scala> b.prefixLength((x)=>(x+1)%2==0)
res92: Int = 2
返回元素的乘积
scala> var b = Array(3,5,8,12)
b: Array[Int] = Array(3, 5, 8, 12)scala> b.product
res93: Int = 1440
聚合计算,同fold,无需初始值,返回计算结果
scala> arr
res95: Array[Int] = Array(1, 2, 3, 4, 1, 2)scala> arr.reduce(_+_)
res97: Int = 13scala> arr.reduce(_/_)
res98: Int = 0scala> arr.reduce(_-_)
res99: Int = -11
聚合计算(从左到右与从右到左),同foldLeft与foldRight
scala> arr.reduceLeft(_+_)
res100: Int = 13scala> arr.reduceRight(_+_)
res104: Int = 13
聚合计算(从左到右与从右到左),同reduce\reduceLeft\fold,唯一区别是允许当前序列为空,返回类型是Option
scala> arr.reduceLeftOption(_+_)
res105: Option[Int] = Some(13)
反转数组
scala> arr
res108: Array[Int] = Array(1, 2, 3, 4, 1, 2)scala> arr.reverse
res109: Array[Int] = Array(2, 1, 4, 3, 2, 1)
根据当前序列反向生成迭代器
scala> arr
res108: Array[Int] = Array(1, 2, 3, 4, 1, 2)scala> arr.reverseIterator.toList
res110: List[Int] = List(2, 1, 4, 3, 2, 1)
同map作用,返回序列的方向与map相反
scala> arr
res108: Array[Int] = Array(1, 2, 3, 4, 1, 2)scala> arr.reverseMap(_*2)
res111: Array[Int] = Array(4, 2, 8, 6, 4, 2)
执行偏函数,当参数不在定义域内时,返回false,否则返回true,并执行action
val pf:PartialFunction[Int,Int]={
case m: Int if m % 2 == 1=> m * 2
}# 传参
pf.runWith(println)(3)
6
res36: Boolean = truepf.runWith(println)(2)
res38: Boolean = false
判断两个序列中元素排列和值是否一致,可以实现类似功能的有corresponds(根据条件比较数组)
scala> arr
res120: Array[Int] = Array(1, 2, 3, 4, 1, 2)scala> arr.sameElements(Array(1,2))
res119: Boolean = falsescala> arr.sameElements(Array(1,2,3,4,1,2))
res121: Boolean = true
功能类似于fold,不过此方法将每一个的返回结果放到一个新的数组中返回,而fold值返回最终结果
scala> arr.scan(5)(_+_)
res123: Array[Int] = Array(5, 6, 8, 11, 15, 16, 18)scala> arr
res124: Array[Int] = Array(1, 2, 3, 4, 1, 2)scala> arr.scanLeft(5)(_+_)
res125: Array[Int] = Array(5, 6, 8, 11, 15, 16, 18)scala> arr.scanRight(5)(_+_)
res126: Array[Int] = Array(18, 17, 15, 12, 8, 7, 5)
返回指定下标值后(不包含指定下标),满足表达式的连续元素的个数,不满足就停止
scala> arr
res127: Array[Int] = Array(1, 2, 3, 4, 1, 2)scala> arr.segmentLength(_%2==0,2)
res129: Int = 0scala> arr.segmentLength(_>2,2)
res132: Int = 2
产生一个引用当前序列的 sequential 视图
scala> arr
res127: Array[Int] = Array(1, 2, 3, 4, 1, 2)scala> arr.seq
res133: scala.collection.mutable.IndexedSeq[Int] = WrappedArray(1, 2, 3, 4, 1, 2)
返回数组长度
scala> arr
res127: Array[Int] = Array(1, 2, 3, 4, 1, 2)scala> arr.size
res134: Int = 6
数组切片:从from到util(前包含,后不包含),类似的功能方法有:init(返回去除最后一个元素的序列)
scala> arr
res138: Array[Int] = Array(1, 2, 3, 4, 1, 2)scala> arr.slice(2,5)
res137: Array[Int] = Array(3, 4, 1)
def sliding(size: Int,step: Int): Iterator[Array[Int]]
def sliding(size: Int): Iterator[Array[Int]]
按照步长(不写默认1)滑动切分数组(数组中size个元素),返回一个数组的可迭代集合
scala> arr
res139: Array[Int] = Array(1, 2, 3, 4, 1, 2)scala> arr.sliding(3)
res140: Iterator[Array[Int]] = non-empty iteratorscala> arr.sliding(3).toList
res141: List[Array[Int]] = List(Array(1, 2, 3), Array(2, 3, 4), Array(3, 4, 1), Array(4, 1, 2))scala> arr.sliding(3,1).toList
res142: List[Array[Int]] = List(Array(1, 2, 3), Array(2, 3, 4), Array(3, 4, 1), Array(4, 1, 2))scala> arr.sliding(3,2).toList
res143: List[Array[Int]] = List(Array(1, 2, 3), Array(3, 4, 1), Array(1, 2))scala> arr.sliding(3,4).toList
res144: List[Array[Int]] = List(Array(1, 2, 3), Array(1, 2))scala> arr.sliding(2,4).toList
res145: List[Array[Int]] = List(Array(1, 2), Array(1, 2))
返回按照给定好的条件排序的序列
scala> arr
res151: Array[Int] = Array(1, 2, 3, 4, 1, 2)scala> arr.sortBy(x=>x)
res152: Array[Int] = Array(1, 1, 2, 2, 3, 4)scala> arr.sortBy(x=> -x)
res153: Array[Int] = Array(4, 3, 2, 2, 1, 1)
按照自定义排序方法排序
scala> arr.sortWith(_.compareTo(_)>1)
res154: Array[Int] = Array(1, 2, 3, 4, 1, 2)scala> arr.sortWith(_.compareTo(_)>0)
res156: Array[Int] = Array(4, 3, 2, 2, 1, 1)
默认升序排序
scala> arr.sorted
res158: Array[Int] = Array(1, 1, 2, 2, 3, 4)scala> arr
res159: Array[Int] = Array(1, 2, 3, 4, 1, 2)
找到第一个满足条件元素,开始分割序列为两个集合,碰到第一个不满足则停止分区,返回一个元组,该元组第一个元素为符合条件的序列,第二个为不符合的序列
scala> arr
res159: Array[Int] = Array(1, 2, 3, 4, 1, 2)scala> arr.span(_>=2)
res160: (Array[Int], Array[Int]) = (Array(),Array(1, 2, 3, 4, 1, 2))scala> arr.span((x)=>(x+1)%2==0)
res161: (Array[Int], Array[Int]) = (Array(1),Array(2, 3, 4, 1, 2))
返回元组,第一个是包含当前序列前n个元素的序列,第二个是其余元素的序列
scala> arr.splitAt(2)
res162: (Array[Int], Array[Int]) = (Array(1, 2),Array(3, 4, 1, 2))scala> arr.splitAt(5)
res163: (Array[Int], Array[Int]) = (Array(1, 2, 3, 4, 1),Array(2))
数组是否从指定下标开始是某个序列
scala> arr
res166: Array[Int] = Array(1, 2, 3, 4, 1, 2)scala> arr.startsWith(Array(3,4),2)
res167: Boolean = truescala> arr.startsWith(Array(3,4),5)
res168: Boolean = false
返回toString结果内存地址的前缀
scala> arr.stringPrefix
res169: String = [Iscala> arr
res170: Array[Int] = Array(1, 2, 3, 4, 1, 2)
数组元素求和
scala> arr
res170: Array[Int] = Array(1, 2, 3, 4, 1, 2)scala> arr.sum
res171: Int = 13
返回除了当前序列第一个元素的其他元素组成的序列,可联合init记忆
scala> arr
res172: Array[Int] = Array(1, 2, 3, 4, 1, 2)scala> arr.tail
res173: Array[Int] = Array(2, 3, 4, 1, 2)
对当前序列进行反复的tail操作,直到tail返回的结果为空,联合inits记忆
scala> arr.tails.toList
res175: List[Array[Int]] = List(Array(1, 2, 3, 4, 1, 2), Array(2, 3, 4, 1, 2), Array(3, 4, 1, 2), Array(4, 1, 2), Array(1, 2), Array(2), Array())
返回当前序列中前n个元素组成的序列
scala> arr
res177: Array[Int] = Array(1, 2, 3, 4, 1, 2)scala> arr.take(3)
res178: Array[Int] = Array(1, 2, 3)
从尾元素开始,返回n个元素的序列
scala> arr
res179: Array[Int] = Array(1, 2, 3, 4, 1, 2)scala> arr.takeRight(4)
res180: Array[Int] = Array(3, 4, 1, 2)
从第一个元素开始,返回序列中满足条件的连续元素的序列,可联系find、maxBy、minBy记忆,这三者都是返回元素
scala> arr
res185: Array[Int] = Array(1, 2, 3, 4, 1, 2)scala> arr.takeWhile(x=>(x+1)%2==0)
res186: Array[Int] = Array(1)scala> arr.takeWhile(_>2)
res187: Array[Int] = Array()
返回数组
scala> arr.to
res189: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 2, 3, 4, 1, 2)
返回当前序列转换为Array类型
scala> arr
res191: Array[Int] = Array(1, 2, 3, 4, 1, 2)scala> arr.toArray
res192: Array[Int] = Array(1, 2, 3, 4, 1, 2)
返回当前序列转换为Buffer类型
scala> arr
res193: Array[Int] = Array(1, 2, 3, 4, 1, 2)scala> arr.toBuffer
res194: scala.collection.mutable.Buffer[Int] = ArrayBuffer(1, 2, 3, 4, 1, 2)
转换成immutable.IndexedSeq对象
scala> arr
res195: Array[Int] = Array(1, 2, 3, 4, 1, 2)scala> arr.toIndexedSeq
res196: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 2, 3, 4, 1, 2)
转换为迭代器
scala> arr
res195: Array[Int] = Array(1, 2, 3, 4, 1, 2)scala> arr.toIterable
res197: Iterable[Int] = WrappedArray(1, 2, 3, 4, 1, 2)scala> arr.toIterator.toList
res199: List[Int] = List(1, 2, 3, 4, 1, 2)
将当前序列转换成List类型序列,并返回
scala> arr
res200: Array[Int] = Array(1, 2, 3, 4, 1, 2)scala> arr.toList
res201: List[Int] = List(1, 2, 3, 4, 1, 2)
同Map 类型,需要被转化序列中包含的元素时 Tuple2 类型数据
scala> val chars = Array((7,5),(12,45),(16,15))
chars: Array[(Int, Int)] = Array((7,5), (12,45), (16,15))scala> chars.toMap
res205: scala.collection.immutable.Map[Int,Int] = Map(7 -> 5, 12 -> 45, 16 -> 15)
转换成Set类型
scala> arr
res206: Array[Int] = Array(1, 2, 3, 4, 1, 2)scala> arr.toSeq
res207: Seq[Int] = WrappedArray(1, 2, 3, 4, 1, 2)
同Stream(流)类型
scala> arr
res208: Array[Int] = Array(1, 2, 3, 4, 1, 2)scala> arr.toStream
res209: scala.collection.immutable.Stream[Int] = Stream(1, ?)
转换为包装数组
scala> arr
res210: Array[Int] = Array(1, 2, 3, 4, 1, 2)scala> arr.toTraversable
res215: Traversable[Int] = WrappedArray(1, 2, 3, 4, 1, 2)
转化为向量集Vector 类型
scala> arr
res212: Array[Int] = Array(1, 2, 3, 4, 1, 2)scala> arr.toVector
res213: Vector[Int] = Vector(1, 2, 3, 4, 1, 2)
矩阵转换,二维数组行列转换
val k = Array(Array(1,2),Array(3,4),Array(5,6))
k.transpose
res345: Array[Array[Int]] = Array(Array(1, 3, 5), Array(2, 4, 6))val k = Array(Array(1,2),Array(3,4),Array(5))
res346: Array[Array[Int]] = Array(Array(1, 3, 5), Array(2, 4))k.transpose.transpose
res347: Array[Array[Int]] = Array(Array(1, 2), Array(3, 4), Array(5))
联合两个序列,同操作符++
scala> arr
res219: Array[Int] = Array(1, 2, 3, 4, 1, 2)scala> str
res220: Array[String] = Array(zhangsan, lisi, wangwu)scala> str union arr
res221: Array[Any] = Array(zhangsan, lisi, wangwu, 1, 2, 3, 4, 1, 2)
将含有元组的数组中元组的第一个元素组成一个序列,第二个元素组成一个序列
注:元组有且只能由两个元素
scala> var a = Array((15,12),(22,55))
a: Array[(Int, Int)] = Array((15,12), (22,55))scala> a.unzip
res227: (Array[Int], Array[Int]) = (Array(15, 22),Array(12, 55))
将含有三个元素的三个数组,第一个元素取出组成一个序列,第二个元素组成一个序列,第三个元素组成一个序列
注:元组有且只能由三个元素
scala> var c = Array((15,1,2),(22,5,5))
c: Array[(Int, Int, Int)] = Array((15,1,2), (22,5,5))scala> c.unzip3
res229: (Array[Int], Array[Int], Array[Int]) = (Array(15, 22),Array(1, 5),Array(2, 5))
def update(i: Int,x: Int): Unit
将序列中 i 索引处的元素更新为 x,无返回值
注:无返回值,不能用变量去接
scala> arr
res233: Array[Int] = Array(1, 2, 3, 4, 1, 2)scala> arr.update(3,16)scala> arr
res235: Array[Int] = Array(1, 2, 3, 16, 1, 2)
更新数组,返回更新后的数组
scala> arr
res237: Array[Int] = Array(1, 2, 3, 16, 1, 2)scala> arr.updated(2,78)
res238: Array[Int] = Array(1, 2, 78, 16, 1, 2)
返回from到until间的元素,前包后不包,有点类似于切片slice,可联合记忆
scala> arr
res242: Array[Int] = Array(1, 2, 3, 16, 1, 2)scala> arr.view(2,5).toArray
res243: Array[Int] = Array(3, 16, 1)
根据条件过滤元素,类似于filter,不过需要用map取出才能有一样的效果
scala> arr
res247: Array[Int] = Array(1, 2, 3, 16, 1, 2)scala> arr.withFilter((x)=>(x+1)%2==0).map(x=>x)
res248: Array[Int] = Array(1, 3, 1)
upzip的反方向转换,将两个序列对应位置上的元素组成一个元组序列,不会自动补充
scala> arr
res249: Array[Int] = Array(1, 2, 3, 16, 1, 2)scala> b
res250: Array[Int] = Array(3, 5, 8, 12)scala> arr.zip(b)
res252: Array[(Int, Int)] = Array((1,3), (2,5), (3,8), (16,12))
使用范式:def zipAll[B](that: collection.Iterable[B], thisElem: A, thatElem: B): Array[(A, B)]
使用说明:同zip,但是允许两个序列长度不一样,不足的自动补充
注:如果当前序列that相对长,空出的填充为 thisElem,如果 that 短,填充为 thatElem
scala> arr
res266: Array[Int] = Array(1, 2, 3, 16, 1, 2)scala> b
res267: Array[Int] = Array(3, 5, 8, 12)scala> arr.zipAll(b,7,46)
res268: Array[(Int, Int)] = Array((1,3), (2,5), (3,8), (16,12), (1,46), (2,46))scala> b.zipAll(arr,7,46)
res269: Array[(Int, Int)] = Array((3,1), (5,2), (8,3), (12,16), (7,1), (7,2))
使用范式:def zipWithIndex: Array[(A, Int)]
使用说明:序列中的每个元素和它的索引组成一个元组序列
scala> arr
res271: Array[Int] = Array(1, 2, 3, 16, 1, 2)scala> arr.zipWithIndex
res272: Array[(Int, Int)] = Array((1,0), (2,1), (3,2), (16,3), (1,4), (2,5))
下一篇:天微亮,该醒了的情侣名是?