Scala学习笔记(二)--------数组Array方法大全(持续更新中) 介绍+演练

Scala 数组

Scala 语言中提供的数组是用来存储固定大小的同类型元素,数组对于每一门编辑语言来说都是重要的数据结构之一。
声明数组变量并不是声明 number0、number1、…、number99 一个个单独的变量,而是声明一个就像 numbers 这样的变量,然后使用 numbers[0]、numbers[1]、…、numbers[99] 来表示一个个单独的变量。数组中某个指定的元素是通过索引来访问的。
数组的第一个元素索引为0,最后一个元素的索引为元素总数减1。

声明数组

var z:Array[String] = new Array[String](3)

或

var z = new Array[String](3)

或最简单的

scala> var arr = Array(1,2,3,4,5,6)
arr: Array[Int] = Array(1, 2, 3, 4, 5, 6)


集合操作

噩梦开篇:
让我们看下Array的所有操作方法:


scala> var arr = Array(1,2,3,4,5,6)
arr: Array[Int] = Array(1, 2, 3, 4, 5, 6)

scala> arr.
++              filterNot            maxBy               span
++:             find                 min                 splitAt
+:              flatMap              minBy               startsWith
/:              flatten              mkString            stringPrefix
:+              fold                 nonEmpty            sum
:\              foldLeft             orElse              tail
addString       foldRight            padTo               tails
aggregate       forall               par                 take
andThen         foreach              partition           takeRight
apply           genericBuilder       patch               takeWhile
applyOrElse     groupBy              permutations        to
array           grouped              prefixLength        toArray
canEqual        hasDefiniteSize      product             toBuffer
clone           head                 reduce              toIndexedSeq
collect         headOption           reduceLeft          toIterable
collectFirst    indexOf              reduceLeftOption    toIterator
combinations    indexOfSlice         reduceOption        toList
companion       indexWhere           reduceRight         toMap
compose         indices              reduceRightOption   toSeq
contains        init                 repr                toSet
containsSlice   inits                reverse             toStream
copyToArray     intersect            reverseIterator     toTraversable
copyToBuffer    isDefinedAt          reverseMap          toVector
corresponds     isEmpty              runWith             transform
count           isTraversableAgain   sameElements        transpose
deep            iterator             scan                union
diff            last                 scanLeft            unzip
distinct        lastIndexOf          scanRight           unzip3
drop            lastIndexOfSlice     segmentLength       update
dropRight       lastIndexWhere       seq                 updated
dropWhile       lastOption           size                view
elemManifest    length               slice               withFilter
elemTag         lengthCompare        sliding             zip
endsWith        lift                 sortBy              zipAll
exists          map                  sortWith            zipWithIndex
filter          max                  sorted


开始介绍用法:

  1. ++
    def ++[B](that: GenTraversableOnce[B]): Array[B]
    合并集合,并返回一个新的数组,新数组包含左右两个集合对象的内容。
scala> var a = Array(1,2,3)
a: Array[Int] = Array(1, 2, 3)

scala> var b = Array(4,5,6)
b: Array[Int] = Array(4, 5, 6)

scala> a ++ b
res0: Array[Int] = Array(1, 2, 3, 4, 5, 6)

  1. ++:
    def ++:[B >: A, That](that: collection.Traversable[B])(implicit bf: CanBuildFrom[Array[T], B, That]): That
    这个方法同上一个方法类似,两个加号后面多了一个冒号,但是不同的是右边操纵数的类型决定着返回结果的类型。下面代码中Array和List结合,返回结果是List类型
scala> var a = Array(1,2,3)
a: Array[Int] = Array(1, 2, 3)

scala> var c = List(4,5,6)
c: List[Int] = List(4, 5, 6)

scala> a ++: c
res1: List[Int] = List(1, 2, 3, 4, 5, 6

  1. +:以及 :+
    def +:(elem: A): Array[A]
    def :+(elem: A): Array[A]

    +:   是在数组前面添加一个元素,并返回新的对象,下面添加一个元素 0。
    :+   同上面的方法相仿,但是是在数组末尾添加一个元素,并返回新对象
scala> var k=100
k: Int = 100

scala>  k++ arr
<console>:14: error: value ++ is not a member of Int
        k++ arr
         ^
// ++是无法加进去的
scala> k +: arr
res27: Array[Int] = Array(100, 1, 2, 3, 4, 5, 6)

scala>  arr :+ k
res28: Array[Int] = Array(1, 2, 3, 4, 5, 6, 100)

scala> k +: a
res29: List[Int] = List(100, 3, 4, 5)
//List也是可以加的 但是不可改

  1. /::\
    def /:[B](z: B)(op: (B, T) ⇒ B): B
    def :[B](z: B)(op: (T, B) ⇒ B): B

    /:    对数组中所有的元素进行相同的操作 ,foldLeft的简写
    :\    foldRight的简写
scala> k
res30: Int = 100

scala> a
res31: List[Int] = List(3, 4, 5)

scala> (100 /: a)(_+_)
res32: Int = 112
//计算顺序是: 100+3 -> 103+4 -> 107+5 -> 112

scala> (a :\ 100)(_+_)
res33: Int = 112
//计算顺序是: 3+4 -> 7+5 -> 12+100 -> 112

scala> (100 :\ a)(_+_)
<console>:13: error: value :\ is not a member of Int
       (100 :\ a)(_+_)
            ^
//左右的数值类型要对应 冒号在哪边 集合就在哪边

  1. addString
    def addString(b: StringBuilder): StringBuilder
    将数组中的元素逐个添加到b中
scala> val a = List(3,4,5)
a: List[Int] = List(3, 4, 5)
scala> var str = new StringBuilder
str: StringBuilder =

scala> a.addString(str)
res35: StringBuilder = 345

def addString(b: StringBuilder, sep: String): StringBuilder
同上,每个元素用sep分隔符分开

scala> a.addString(str,"#")
res37: StringBuilder = 3453#4#5

def addString(b: StringBuilder, start: String, sep: String, end: String): StringBuilder
同上,在首尾各加一个字符串,并指定sep分隔符

scala> var str=new StringBuilder
str: StringBuilder =

scala> a.addString(str,"[",",","]")
res38: StringBuilder = [3,4,5]

  1. aggregate
    def aggregate[B](z: ⇒ B)(seqop: (B, T) ⇒ B, combop: (B, B) ⇒ B): B
    聚合计算,aggregate是柯里化方法,参数是两个方法,为了方便理解,我们把aggregate的两个参数,分别封装成两个方法,并把计算过程打印出来。
在这之前首先解释一下par(分区的概念):
Scala为了充分使用多核CPU,提供了并行集合(有别于前面的串行集合),用于多核环境的并行计算。
主要用到的算法有:
Divide and conquer : 分治算法,Scala通过splitters,combiners等抽象层来实现,主要原理是将计算工作分解很多任务,分发给一些处理器去完成,并将它们处理结果合并返回
Work stealin:算法,主要用于任务调度负载均衡(load-balancing),通俗点完成自己的所有任务之后,发现其他人还有活没干完,主动(或被安排)帮他人一起干,这样达到尽早干完的目的。

scala> (1 to 5).foreach(println(_))
1
2
3
4
5

scala> (1 to 5).par.foreach(println(_))
3
1
4
2
5

再来说aggregate:

  	scala> val arr =List(List(1,2,3),List(3,4,5),List(2),List(0));
	arr: List[List[Int]] = List(List(1, 2, 3), List(3, 4, 5), List(2), List(0))

	scala> arr.aggregate(0)(_+_.reduce(_+_),_+_);
	res18: Int = 20

	//第一个_代表累加后的值,就是先做局部运算
	//第二个.reduce(+_) 代表 每一个 内部List 进行汇总运算

	//运算步骤:+.reduce(+)) 先计算 list1 1+2+3 6+.reduce(+)) 再计算list2 3+4+5 12+.reduce(+)) list3计算 2+.reduce(+)) list4计算 0

	//以上局部变量就计算完了
	//当list1计算出来的时候就放到 + 初始值为0 + 6
	//然后当list2计算出来的时候 + 值 为 2+12
	//后面依次相加 …

	//下面这两种写法都可以

arr.aggregate(10)(+.sum,+)

arr.par.aggregate(10)(+.sum,+)

  1. apply
    def apply(i: Int): T
    取出指定索引处的元素
scala> var c = Array(23,34,5,76,88,881)
c: Array[Int] = Array(23, 34, 5, 76, 88, 881)

scala> c.apply(2)
res0: Int = 5

  1. canEqual
    def canEqual(that: Any): Boolean
    判断两个对象是否可以进行比较
scala> var c = Array(23,34,5,76,88,881)
c: Array[Int] = Array(23, 34, 5, 76, 88, 881)

scala> var d = Array(2,3,45,5)
d: Array[Int] = Array(2, 3, 45, 5)

scala> c.canEqual(d)
res2: Boolean = true //同数组可以比较

scala> c.canEqual('z')
res3: Boolean = true

scala> object myObj{}
defined object myObj

scala> c.canEqual(myObj)
res4: Boolean = true	//对象也可以比较

//理论上讲数组可以和大部分都可以比较

  1. charAt
    def charAt(index: Int): Char
    获取index索引处的字符,这个方法会执行一个隐式的转换,将Array[T]转换为 ArrayCharSequence,只有当T为char类型时,这个转换才会发生。
scala> var e = Array('a','b','b')
e: Array[Char] = Array(a, b, b)

scala> e.charAt(1)
res5: Char = b

  1. clone
    def clone(): Array[T]
    创建一个副本
scala> var c = Array(23,34,5,76,88,881)
c: Array[Int] = Array(23, 34, 5, 76, 88, 881)

scala> var e = c
e: Array[Int] = Array(23, 34, 5, 76, 88, 881)

scala> c
res6: Array[Int] = Array(23, 34, 5, 76, 88, 881)

scala> c(2)=44

scala> c
res8: Array[Int] = Array(23, 34, 44, 76, 88, 881)

scala> e
res9: Array[Int] = Array(23, 34, 44, 76, 88, 881)

直接赋值的本体变了 副本也会变

scala> var k = c.clone
k: Array[Int] = Array(23, 34, 44, 76, 88, 881)

scala> c(2)=100

scala> c
res11: Array[Int] = Array(23, 34, 100, 76, 88, 881)

scala> k
res12: Array[Int] = Array(23, 34, 44, 76, 88, 881)

//拷贝副本 本体值改了 克隆体的值不会改变

  1. 重点: collect
    def collect[B](pf: PartialFunction[A, B]): Array[B]
    通过执行一个并行计算(偏函数),得到一个新的数组对象
    偏函数概念:
    在Scala中,偏函数是具有类型PartialFunction[-T,+V]的一种函数。T是其接受的函数类型,V是其返回的结果类型。偏函数最大的特点就是它只接受和处理其参数定义域的一个子集,而对于这个子集之外的参数则抛出运行时异常。这与Case语句的特性非常契合,因为我们在使用case语句是,常常是匹配一组具体的模式,最后用“_”来代表剩余的模式。如果一一组case语句没有涵盖所有的情况,那么这组case语句就可以被看做是一个偏函数。
scala> c
res11: Array[Int] = Array(23, 34, 100, 76, 88, 881)

scala> val fun:PartialFunction[Int,Int] ={
     |   case x=> x+1	//所有数都+1
     | }
fun: PartialFunction[Int,Int] = <function1>

scala> c.collect(fun)
res13: Array[Int] = Array(24, 35, 101, 77, 89, 882)



scala> val fun:PartialFunction[Int,Int] ={
     |   case 23 => 123
     | }
fun: PartialFunction[Int,Int] = <function1>
// 不写case x => x的话 其他进不去 所以偏函数将其他都去掉了
scala> c.collect(fun)
res14: Array[Int] = Array(123)


scala> val fun:PartialFunction[Int,Int] ={
     |   case 23 => 123				//遇到23 换成123
     |   case y if y%2==0 => y+1000	//偶数+1000
     |   case x =>x					//其他值不变
     | }
fun: PartialFunction[Int,Int] = <function1>

scala> c.collect(fun)
res16: Array[Int] = Array(123, 1034, 1100, 1076, 1088, 881)


scala> val fun:PartialFunction[Int,String] ={
     | case 23 => "xixi"		//23 换成xiix
     | case y if y%2==0 =>"gg"	//偶数 换成gg
     | case x => x+"ff"			//其他值+ff
     | }
fun: PartialFunction[Int,String] = <function1>

scala> c.collect(fun)
res17: Array[String] = Array(xixi, gg, gg, gg, gg, 881ff)

  1. collectFirst
    def collectFirst[B](pf: PartialFunction[T, B]): Option[B]
    在序列中查找第一个符合偏函数定义的元素,并执行偏函数计算
val arr = Array(1,'a',"b")
//定义一个偏函数,要求当被执行对象为Int类型时,进行乘100的操作,对于上面定义的对象arr来说,只有第一个元素符合要求
  val fun:PartialFunction[Any,Int] = {
    case x:Int => x*100
  }
//计算
  val value = arr.collectFirst(fun)
  println("value:"+value)
//另一种写法
val value = arr.collectFirst({case x:Int => x*100})

  1. combinations
    def combinations(n: Int): collection.Iterator[Array[T]]
    排列组合,这个排列组合会选出所有包含字符不一样的组合,对于 “abc”、“cba”,只选择一个,参数n表示序列长度,就是几个字符为一组
scala> c
res19: Array[Int] = Array(23, 34, 100, 76, 88, 881)

scala> c.combinations(3)
res20: Iterator[Array[Int]] = non-empty iterator
//迭代器只能操作一遍  但是数组可以执行多次

scala> c.combinations(3)    //返回几几组合的不重复的组合
res20: Iterator[Array[Int]] = non-empty iterator

scala> var ee = c.combinations(3)
ee: Iterator[Array[Int]] = non-empty iterator

scala> ee.foreach(x=>println(x.mkString(",")))	//把数组中字符以“,”连在一起
23,34,100
23,34,76
23,34,88
23,34,881
23,100,76
23,100,88
23,100,881
23,76,88
23,76,881
23,88,881
34,100,76
34,100,88
34,100,881
34,76,88
34,76,881
34,88,881
100,76,88
100,76,881
100,88,881
76,88,881

  1. contains
    def contains[A1 >: A](elem: A1): Boolean
    序列中是否包含指定对象
scala> c
res22: Array[Int] = Array(23, 34, 100, 76, 88, 881)

scala> c.contains(50)
res23: Boolean = false

scala> c.contains(23)
res24: Boolean = true

  1. containsSlice
    def containsSlice[B](that: GenSeq[B]): Boolean
    判断当前序列中是否包含另一个序列
scala> var d = Array(23,34,50)
d: Array[Int] = Array(23, 34, 50)

scala> c
res25: Array[Int] = Array(23, 34, 100, 76, 88, 881)

scala> c.containsSlice(d)
res26: Boolean = false

//删除d中的50
scala> d
res27: Array[Int] = Array(23, 34, 50)

scala> d.dropRight(1)
res28: Array[Int] = Array(23, 34)

scala> d
res29: Array[Int] = Array(23, 34, 50)

scala> k = d.dropRight(1)
k: Array[Int] = [I@72cf43fa

scala> k
res30: Array[Int] = Array(23, 34)

scala> c.containsSlice(k)
res32: Boolean = true

  1. copyToArray
    def copyToArray(xs: Array[A]): Unit
    def copyToArray(xs: Array[A], start: Int): Unit
    def copyToArray(xs: Array[A], start: Int, len: Int): Unit
scala> val a =Array(0,0,0,0,0,0,0)
a: Array[Int] = Array(0, 0, 0, 0, 0, 0, 0)

scala> c
res33: Array[Int] = Array(23, 34, 100, 76, 88, 881)

scala> c.copyToArray(a,2)

scala> a
res35: Array[Int] = Array(0, 0, 23, 34, 100, 76, 88)
//拷贝c的内容到a中 从a的第二个位置开始拷贝

  1. copyToBuffer
    def copyToBuffer[B >: A](dest: Buffer[B]): Unit
    将数组中的内容拷贝到Buffer中 数组变集合
scala> import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.ArrayBuffer

scala> var a :ArrayBuffer[Int] = ArrayBuffer()
a: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer()

scala> val c = Array(23, 34, 100, 76, 88, 881)
c: Array[Int] = Array(23, 34, 100, 76, 88, 881)

scala> c.copyToBuffer(a)


scala> a
res41: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(23, 34, 100, 76, 88, 881)

//和前一个差不多 但是只能全量拷贝

  1. corresponds
    def corresponds[B](that: GenSeq[B])(p: (T, B) ⇒ Boolean): Boolean
    判断两个序列长度以及对应位置元素是否符合某个条件。如果两个序列具有相同的元素数量并且p(x, y)=true,返回结果为true
scala> c
res43: Array[Int] = Array(23, 34, 100, 76, 88, 881)

scala> c.corresponds(a)(_==_)
res38: Boolean = true

scala> a
res39: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(23, 34, 100, 76, 88, 881)

scala> a.remove(3)
res40: Int = 76

scala> c.corresponds(a)(_==_)
res41: Boolean = false

scala> a
res42: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(23, 34, 100, 88, 881)

  1. 重点: count
    def count(p: (T) ⇒ Boolean): Int
    统计符合条件的元素个数,下面统计偶数元素个数
scala> c.count(p=>p%2==0) 	//count后面带条件 统计符合条件的个数
res46: Int = 4

scala> c
res47: Array[Int] = Array(23, 34, 100, 76, 88, 881)

  1. diff
    def diff(that: collection.Seq[T]): Array[T]
    计算当前数组与另一个数组的不同。将当前数组中没有在另一个数组中出现的元素返回
scala> c
res47: Array[Int] = Array(23, 34, 100, 76, 88, 881)

scala> a
res48: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(23, 34, 100, 88, 881)

scala> c.diff(a)
res49: Array[Int] = Array(76)

  1. distinct
    def distinct: Array[T]
    去除当前集合中重复的元素,只保留一个
scala> c
res51: Array[Int] = Array(23, 34, 100, 76, 88, 881)

scala> c= c :+ 23
c: Array[Int] = [I@2e353ae8

scala> c
res52: Array[Int] = Array(23, 34, 100, 76, 88, 881, 23)

scala> c.distinct
res53: Array[Int] = Array(23, 34, 100, 76, 88, 881)

  1. 重点: drop
    def drop(n: Int): Array[T]
    将当前序列中前 n 个元素去除后,作为一个新序列返回
val a = Array(1, 2, 3,4)
val c = a.drop(2)
println(c.mkString(","))    // 3,4

  1. dropRight
    def dropRight(n: Int): Array[T]
    功能同 drop,去掉尾部的 n 个元素
scala> d
res27: Array[Int] = Array(23, 34, 50)

scala> d.dropRight(1)
res28: Array[Int] = Array(23, 34)

  1. dropWhile.
    def dropWhile(p: (T) ⇒ Boolean): Array[T]
    去除当前数组中符合条件的元素,这个需要一个条件,就是从当前数组的第一个元素起,就要满足条件,直到碰到第一个不满足条件的元素结束(即使后面还有符合条件的元素),否则返回整个数组
scala> a
res55: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(23, 34, 100, 88, 881)

scala> a.dropWhile(p=>p%2==1)
res54: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(34, 100, 88, 881)

  1. endsWith
    def endsWith[B](that: GenSeq[B]): Boolean
    判断是否以某个序列结尾
scala> var a = Array(3,2,3,4)
a: Array[Int] = Array(3, 2, 3, 4)

scala> val c = Array(2,3,4)
c: Array[Int] = Array(2, 3, 4)

scala> a.endsWith(c)
res58: Boolean = true

  1. exists
    def exists(p: (T) ⇒ Boolean): Boolean
    判断当前数组是否包含符合条件的元素
scala> a
res61: Array[Int] = Array(3, 2, 3, 4)

scala> a.exists(p=>p>5)
res59: Boolean = false

scala> a.exists(p=>p>2)
res60: Boolean = true

  1. 重点: filter    重中之重!!!不会用就等死8
    def filter(p: (T) ⇒ Boolean): Array[T]
    取得当前数组中符合条件的元素,组成新的数组返回.
scala> a
res61: Array[Int] = Array(3, 2, 3, 4)

scala> a.filter(p=>p%2==0)
res62: Array[Int] = Array(2, 4)

关于filter的高阶函数写法:

//怎么在filter里面嵌入自己写的函数: 简单演示
scala> def myfun(p:Int):Boolean={
     | p%2==0
     | }
myfun: (p: Int)Boolean

scala> a
res63: Array[Int] = Array(3, 2, 3, 4)

scala> a.filter(myfun)
res64: Array[Int] = Array(2, 4)

  1. filterNot
    def filterNot(p: (T) ⇒ Boolean): Array[T]
    与上面的 filter 作用相反
scala> a.filterNot(myfun)
res65: Array[Int] = Array(3, 3)

  1. find
    def find(p: (T) ⇒ Boolean): Option[T]

查找第一个符合条件的元素

scala> a
res66: Array[Int] = Array(3, 2, 3, 4)

scala> a.find(x=>x==2)
res67: Option[Int] = Some(2)

scala> a.find(x=>x==2).get
res68: Int = 2
//some数组必须用get方法才能读出来

  1. 重点: flatMap
    def flatMap[B](f: (A) ⇒ GenTraversableOnce[B]): Array[B]
    对当前序列的每个元素进行操作,结果放入新序列返回,参数要求是GenTraversableOnce及其子类

先map再flat:

scala> val c = Array(4,5,6)
c: Array[Int] = Array(4, 5, 6)

//flatmap将map的结果扁平化了 将里面的元素释放出来
scala> c.flatMap(x=>(1 to x))
res69: Array[Int] = Array(1, 2, 3, 4, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 6)

scala> c.map(x=>(1 to x))
res70: Array[scala.collection.immutable.Range.Inclusive] = Array(Range(1, 2, 3, 4), Range(1, 2, 3, 4, 5), Range(1, 2, 3, 4, 5, 6))

scala> c.map(x=>(1 to x)).flatten
res71: Array[Int] = Array(1, 2, 3, 4, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 6)

有个很重要的概念:
map().flatten = flatMap()

  1. flatten[U]
    def flatten[U](implicit asTrav: (T) ⇒ collection.Traversable[U], m: ClassTag[U]): Array[U]
    将二维数组的所有元素联合在一起,形成一个一维数组返回
val dArr = Array(Array(1,2,3),Array(4,5,6))
val c = dArr.flatten
println(c.mkString(","))    //1,2,3,4,5,6

  1. 重点: fold
    def fold[A1 >: A](z: A1)(op: (A1, A1) ⇒ A1): A1

对序列中的每个元素进行二元运算,和aggregate有类似的语义,但执行过程有所不同,我们来对比一下他们的执行过程。
对于fold我们需要了解一个柯里化的概念。
在js中我们举个小例子:

在这里插入图片描述
如最后的console就是函数柯里化的表现。
Scala 函数柯里化(Currying):柯里化(Currying)指的是将原来接受两个参数的函数变成新的接受一个参数的函数的过程。新的函数返回一个以原有第二个参数为参数的函数。

scala> c.fold(5)(_+_)
res72: Int = 20

scala> c
res73: Array[Int] = Array(4, 5, 6)

scala> c
res73: Array[Int] = Array(4, 5, 6)

scala> def myfun(m:Int,n:Int):Int={
     |  m+n
     | }
myfun: (m: Int, n: Int)Int

scala> c.fold(5)(myfun)
res74: Int = 20

  1. foldLeft
    def foldLeft[B](z: B)(op: (B, T) ⇒ B): B
    从左到右计算,简写方式:def /:[B](z: B)(op: (B, T) ⇒ B): B
def seqno(m:Int,n:Int): Int ={
    val s = "seq_exp=%d+%d"
    println(s.format(m,n))
    return m+n
  }
    val a = Array(1, 2, 3,4)
    val b = a.foldLeft(5)(seqno)
    /** 运算过程
    seq_exp=5+1
    seq_exp=6+2
    seq_exp=8+3
    seq_exp=11+4
    */
    /**
    简写 (5 /: a)(_+_)
    */

  1. foldRight
    def foldRight[B](z: B)(op: (B, T) ⇒ B): B
    从右到左计算,简写方式:def :[B](z: B)(op: (T, B) ⇒ B): B
def seqno(m:Int,n:Int): Int ={
    val s = "seq_exp=%d+%d"
    println(s.format(m,n))
    return m+n
  }
    val a = Array(1, 2, 3,4)
    val b = a.foldRight(5)(seqno)
    /** 运算过程
    seq_exp=4+5
    seq_exp=3+9
    seq_exp=2+12
    seq_exp=1+14
    */
    /**
    简写 (a :\ 5)(_+_)
    */

  1. forall
    def forall(p: (T) ⇒ Boolean): Boolean
    检测序列中的元素是否都满足条件 p ,如果序列为空,返回true
  	val a = Array(1, 2, 3,4)
    val b = a.forall( {x:Int => x>0})   //true
    val b = a.forall( {x:Int => x>2})   //false

  1. 重点: foreach
    def foreach(f: (A) ⇒ Unit): Unit
      遍历序列中的元素,进行 f 操作
val a = Array(1, 2, 3,4)
    a.foreach(x => println(x*10))
    /**
    10
    20
    30
    40
    */

重点: group    group都不会的话 亲~这边建议不要学scala

  1. groupBy
    def groupBy[K](f: (T) ⇒ K): Map[K, Array[T]]
    按条件分组,条件由 f 匹配,返回值是Map类型,每个key对应一个序列,下面代码实现的是,把小于3的数字放到一组,大于3的放到一组,返回Map[String,Array[Int]]
scala> val k = Array(34,55,776,8,67)
k: Array[Int] = Array(34, 55, 776, 8, 67)

//按照奇偶分组
scala> k.groupBy(x=> x match {
     |    case x if x%2==0  =>  "ou"
     |    case _=> "ji"
     | })
res79: scala.collection.immutable.Map[String,Array[Int]] = Map(ou -> Array(34, 776, 8), ji -> Array(55, 67))

  1. grouped
    def grouped(size: Int): collection.Iterator[Array[T]]
    按指定数量分组,每组有 size 数量个元素, 返回一个集合
scala> val k = Array(34,55,776,8,67)
k: Array[Int] = Array(34, 55, 776, 8, 67

scala> k.grouped(3).foreach(x=>println(x.mkString(",")))
34,55,776
8,67

  1. hasDefiniteSize
    def hasDefiniteSize: Boolean
    检测序列是否存在有限的长度,对应Stream这样的流数据,返回false
scala> val k = Array(34,55,776,8,67)
k: Array[Int] = Array(34, 55, 776, 8, 67)

scala> k.hasDefiniteSize
res81: Boolean = true

  1. head
    def head: T
    返回序列的第一个元素,如果序列为空,将引发错误
scala> val k = Array(34,55,776,8,67)
k: Array[Int] = Array(34, 55, 776, 8, 67)

scala> k.head
res82: Int = 34

  1. headOption
    def headOption: Option[T]
    返回Option类型对象,就是scala.Some 或者 None,如果序列是空,返回None
scala> var lst = ArrayBuffer()
lst: scala.collection.mutable.ArrayBuffer[Nothing] = ArrayBuffer()

scala> lst.headOption
res89: Option[Nothing] = None

  1. indexOf
    def indexOf(elem: T): Int
    返回elem在序列中的索引,找到第一个就返回
val a = Array(1, 3, 2, 3, 4)
println(a.indexOf(3))   // return 1

def indexOf(elem: T, from: Int): Int
返回elem在序列中的索引,可以指定从某个索引处(from)开始查找,找到第一个就返回


val a = Array(1, 3, 2, 3, 4)
println(a.indexOf(3,2)) // return 3

scala> val a  = (1 to 20)
a: scala.collection.immutable.Range.Inclusive = Range(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20)

scala> a.indexOfSlice((4 to 6))
res90: Int = 3

  1. indexWhere
    def indexWhere(p: (T) ⇒ Boolean): Int
    返回当前序列中第一个满足 p 条件的元素的索引
scala> val a  = (1 to 20)
a: scala.collection.immutable.Range.Inclusive = Range(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20)

scala> a.indexWhere(p=>p>5)
res92: Int = 5

  1. indices
    def indices: collection.immutable.Range
    返回当前序列索引集合 取下标
scala> val a  = (1 to 20)
a: scala.collection.immutable.Range.Inclusive = Range(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20)


scala> a.indices
res93: scala.collection.immutable.Range = Range(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19)

  1. 重点: init
    def init: Array[T]去尾
    返回当前序列中不包含最后一个元素的序列

scala> val a  = (1 to 20)
a: scala.collection.immutable.Range.Inclusive = Range(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20)

scala> a.init
res94: scala.collection.immutable.Range = Range(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19)

def inits: collection.Iterator[Array[T]]
对集合中的元素进行 init 操作,该操作的返回值中, 第一个值是当前序列的副本,包含当前序列所有的元素,最后一个值是空的,对头尾之间的值进行init操作,上一步的结果作为下一步的操作对象

val a = Array(1, 2, 3, 4, 5)
    val b = a.inits.toList
    for(i <- 1 to b.length){
      val s = "第%d个值:%s"
      println(s.format(i,b(i-1).mkString(",")))
    }
    /**计算结果
    第1个值:1,2,3,4,5
    第2个值:1,2,3,4
    第3个值:1,2,3
    第4个值:1,2
    第5个值:1
    第6个值
    */

  1. intersect
    def intersect(that: collection.Seq[T]): Array[T]
    取两个集合的交集
scala> val a  = (1 to 20)
a: scala.collection.immutable.Range.Inclusive = Range(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20)


scala> var b = (10 to 25)
b: scala.collection.immutable.Range.Inclusive = Range(10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25)

scala> a.intersect(b)
res96: scala.collection.immutable.IndexedSeq[Int] = Vector(10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20)

  1. isDefinedAt
    def isDefinedAt(idx: Int): Boolean
    判断序列中是否存在指定索引
scala> var b = (10 to 25)
b: scala.collection.immutable.Range.Inclusive = Range(10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25)

scala> b.isDefinedAt(20)
res98: Boolean = false

scala> b.isDefinedAt(5)
res99: Boolean = true

  1. isEmpty
    def isEmpty: Boolean
    判断当前序列是否为空
scala> import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.ArrayBuffer

scala> val c = ArrayBuffer()
c: scala.collection.mutable.ArrayBuffer[Nothing] = ArrayBuffer()

scala> c.isEmpty
res101: Boolean = true

  1. isTraversableAgain
    def isTraversableAgain: Boolean (看是不是迭代器----只能遍历一次)
    判断序列是否可以反复遍历,该方法是GenTraversableOnce中的方法,对于 Traversables 一般返回true,对于 Iterators 返回 false,除非被复写
scala> var arr = Array(1,345,65,787,98)
arr: Array[Int] = Array(1, 345, 65, 787, 98)

scala> arr.isTraversableAgain
res0: Boolean = true
//数组可以无限遍历

scala> arr.iterator.isTraversableAgain
res4: Boolean = false
//迭代器只能遍历一次

  1. last
    def last: T
    取得序列中最后一个元素
  val a = Array(1, 2, 3, 4, 5)
    println(a.last) // return  5

  1. lastIndexOf
    def lastIndexOf(elem: T): Int
    取得序列中最后一个等于 elem 的元素的位置
   val a = Array(1, 4, 2, 3, 4, 5)
println(a.lastIndexOf(4))   // return  4

  1. lastIndexOfSlice
    def lastIndexOfSlice[B >: A](that: GenSeq[B]): Int
    判断当前序列中是否包含序列 that,并返回最后一次出现该序列的位置处的索引
   val a = Array(1, 4, 2, 3, 4, 5, 1, 4)
    val b = Array(1, 4)
println(a.lastIndexOfSlice(b))  // return  6

def lastIndexOfSlice[B >: A](that: GenSeq[B], end: Int): Int
判断当前序列中是否包含序列 that,并返回最后一次出现该序列的位置处的索引,可以指定在 end 之前(包括)的元素中查找

 val a = Array(1, 4, 2, 3, 4, 5, 1, 4)
    val b = Array(1, 4)
println(a.lastIndexOfSlice(b,4))    // return  0

  1. lastIndexWhere
    def lastIndexWhere(p: (T) ⇒ Boolean): Int
    返回当前序列中最后一个满足条件 p 的元素的索引
 val a = Array(1, 4, 2, 3, 4, 5, 1, 4)
    val b = Array(1, 4)
println(a.lastIndexWhere( {x:Int => x<2}))  // return  6

def lastIndexWhere(p: (T) ⇒ Boolean, end: Int): Int
返回当前序列中最后一个满足条件 p 的元素的索引,可以指定在 end 之前(包括)的元素中查找

  val a = Array(1, 4, 2, 3, 4, 5, 1, 4)
    val b = Array(1, 4)
println(a.lastIndexWhere( {x:Int => x<2},2))    // return  0

  1. lastOption
    def lastOption: Option[T]
    返回当前序列中最后一个对象
    val a = Array(1, 2, 3, 4, 5)
println(a.lastOption)   // return  Some(5)

  1. length
    def length: Int
    返回当前序列中元素个数
val a = Array(1, 2, 3, 4, 5)
println(a.length)   // return  5

  1. lengthCompare
    def lengthCompare(len: Int): Int
    比较序列的长度和参数 len,根据二者的关系返回不同的值,比较规则是
    length-括号里面的数
scala> arr.lengthCompare(3)
res5: Int = 2

scala> arr.lengthCompare(2)
res6: Int = 3

scala> arr.lengthCompare(7)
res7: Int = -2

scala> arr.lengthCompare(6)
res8: Int = -1

scala> arr.lengthCompare(5)
res9: Int = 0

scala> arr.length
res10: Int = 5

  1. 重点: map
    def map[B](f: (A) ⇒ B): Array[B] 遍历操作
    对序列中的元素进行 f 操作
    举个栗子:
怎么实现wordcount
scala> val str = "hello mysql hello java"
str: String = hello mysql hello java

scala> str.split(" ").map(x=>(x,1)).groupBy(_._1).mapValues(_.size)
res11: scala.collection.immutable.Map[String,Int] = Map(java -> 1, mysql -> 1, hello -> 2)

scala> str.split(" ").map(x=>(x,1)).groupBy(_._1).foreach(x=>{println(x._1,x._2.length)})
(java,1)
(mysql,1)
(hello,2)

  1. max
    def max: A
scala> arr.max
res17: Int = 787

scala> arr
res18: Array[Int] = Array(1, 345, 65, 787, 98)

  1. maxBy
    def maxBy[B](f: (A) ⇒ B): A
    返回序列中第一个符合条件的最大的元素
scala> arr
res18: Array[Int] = Array(1, 345, 65, 787, 98)

scala> arr.maxBy(x=>x>100)
res19: Int = 345

  1. mkString
    def mkString: String
    将所有元素组合成一个字符串
    val a = Array(1, 2, 3, 4, 5)
println(a.mkString) // return  12345

def mkString(sep: String): String
将所有元素组合成一个字符串,以 sep 作为元素间的分隔符

    val a = Array(1, 2, 3, 4, 5)
println(a.mkString(","))    // return  1,2,3,4,5

  1. nonEmpty
    def nonEmpty: Boolean
    判断序列不是空
scala> arr.nonEmpty
res22: Boolean = true

scala> arr
res23: Array[Int] = Array(1, 345, 65, 787, 98)

  1. padTo
    def padTo(len: Int, elem: A): Array[A] 补位
    后补齐序列,如果当前序列长度小于 len,那么新产生的序列长度是 len,多出的几个位值填充 elem,如果当前序列大于等于 len ,则返回当前序列
scala> arr.padTo(10,0)
res25: Array[Int] = Array(1, 345, 65, 787, 98, 0, 0, 0, 0, 0)

scala> arr
res26: Array[Int] = Array(1, 345, 65, 787, 98)

  1. 重点: par
    def par: ParArray[T]
    返回一个并行实现,产生的并行序列,不能被修改
    val a = Array(1, 2, 3, 4, 5)
    val b = a.par   //  "ParArray" size = 5

  1. 重点: partition
    def partition(p: (T) ⇒ Boolean): (Array[T], Array[T])
    按条件将序列拆分成两个新的序列,满足条件的放到第一个序列中,其余的放到第二个序列,下面以序列元素是否是 2 的倍数来拆分
scala> arr.partition(_%2==0)
res32: (Array[Int], Array[Int]) = (Array(98),Array(1, 345, 65, 787))

scala> arr
res33: Array[Int] = Array(1, 345, 65, 787, 98)

  1. patch
    def patch(from: Int, that: GenSeq[A], replaced: Int): Array[A]
    批量替换,从原序列的 from 处开始,后面的 replaced 数量个元素,将被替换成序列 that
scala> arr
res33: Array[Int] = Array(1, 345, 65, 787, 98)

scala> arr1
res34: Array[Int] = Array(1, 2, 3)

scala> arr.patch(0,arr1,1)
res35: Array[Int] = Array(1, 2, 3, 345, 65, 787, 98)

  1. permutations
    def permutations: collection.Iterator[Array[T]]
    排列组合,他与combinations不同的是,组合中的内容可以相同,但是顺序不能相同,combinations不允许包含的内容相同,即使顺序不一样
scala> arr.permutations.toList
res38: List[Array[Int]] = List(Array(1, 345, 65, 787, 98), Array(1, 345, 65, 98, 787), Array(1, 345, 787, 65, 98), Array(1, 345, 787, 98, 65), Array(1, 345, 98, 65, 787), Array(1, 345, 98, 787, 65), Array(1, 65, 345, 787, 98), Array(1, 65, 345, 98, 787), Array(1, 65, 787, 345, 98), Array(1, 65, 787, 98, 345), Array(1, 65, 98, 345, 787), Array(1, 65, 98, 787, 345), Array(1, 787, 345, 65, 98), Array(1, 787, 345, 98, 65), Array(1, 787, 65, 345, 98), Array(1, 787, 65, 98, 345), Array(1, 787, 98, 345, 65), Array(1, 787, 98, 65, 345), Array(1, 98, 345, 65, 787), Array(1, 98, 345, 787, 65), Array(1, 98, 65, 345, 787), Array(1, 98, 65, 787, 345), Array(1, 98, 787, 345, 65), Array(1, 98, 787, 65, 345), Array(345, 1, 65, 787, 98), Array(345, 1, 65, 98, 787), Array(345, 1, 787, 65, 98), Array(345,...

scala> arr.combinations(3).foreach(x=>println(x.mkString(",")))
1,345,65
1,345,787
1,345,98
1,65,787
1,65,98
1,787,98
345,65,787
345,65,98
345,787,98
65,787,98

  1. prefixLength
    def prefixLength(p: (T) ⇒ Boolean): Int
    给定一个条件 p,返回一个前置数列的长度,这个数列中的元素都满足 p
scala> arr.prefixLength(_<787)
res44: Int = 3

scala> arr
res45: Array[Int] = Array(1, 345, 65, 787, 98)

  1. 重点: product
    def product: A
    返回所有元素乘积的值
scala> (1 to 5 ).product
res48: Int = 120

scala> (1 to 5 ).sum
res49: Int = 15

  1. reduce
    def reduce[A1 >: A](op: (A1, A1) ⇒ A1): A1
    同 fold,不需要初始值
scala> arr.reduce(_+_)
res50: Int = 1296

def reduceLeft[B >: A](op: (B, T) ⇒ B): B
从左向右计算

def reduceRight[B >: A](op: (T, B) ⇒ B): B
从右向左计算

def reduceLeftOption[B >: A](op: (B, T) ⇒ B): Option[B]
计算Option,参考reduceLeft

def reduceRightOption[B >: A](op: (T, B) ⇒ B): Option[B]
计算Option,参考reduceRight

  1. reverse
    def reverse: Array[T]
    反转序列
scala> val arr = Array(1,2,3,4,5)
arr: Array[Int] = Array(1, 2, 3, 4, 5)

scala> arr.reverse
res0: Array[Int] = Array(5, 4, 3, 2, 1)



  1. reverseIterator
    def reverseIterator: collection.Iterator[T]
    反向生成迭代
scala> val arr = Array(1,2,3,4,5)
arr: Array[Int] = Array(1, 2, 3, 4, 5)

scala> arr.reverseIterator
res1: Iterator[Int] = non-empty iterator

scala> arr.reverseIterator.foreach((x:Int)=>print(x))
54321
  1. reverseMap
    def reverseMap[B](f: (A) ⇒ B): Array[B]
    同 map 方向相反
scala> arr.reverseMap((_,1))
res57: Array[(Int, Int)] = Array((98,1), (787,1), (65,1), (345,1), (1,1))

  1. sameElements
    def sameElements(that: GenIterable[A]): Boolean
    判断两个序列是否顺序和对应位置上的元素都一样
scala> val arr2 = arr.clone
arr2: Array[Int] = Array(1, 345, 65, 787, 98)

scala> arr.sameElements(arr2)
res58: Boolean = true

  1. 重点: scan 怎么硕呢~ 这玩意一定得会

def scan[B >: A, That](z: B)(op: (B, B) ⇒ B)(implicit cbf: CanBuildFrom[Array[T], B, That]): That
用法同 fold,scan会把每一步的计算结果放到一个新的集合中返回,而 fold 返回的是单一的值

def scanLeft[B, That](z: B)(op: (B, T) ⇒ B)(implicit bf: CanBuildFrom[Array[T], B, That]): That
从左向右计算

def scanRight[B, That](z: B)(op: (T, B) ⇒ B)(implicit bf: CanBuildFrom[Array[T], B, That]): That
从右向左计算

  	val a = Array(1,2,3,4,5)
    val b = a.scan(5)(seqno)
    println(b.mkString(","))    // 5,6,8,11,15,20

举个栗子:求n!

  def main(args: Array[String]): Unit = {
    test(5).foreach(println)
    /*结果:
        1
        1
        2
        6
        24
        120
    */
  }

  def test(n: Int) = {
    (1 to n).scan(1)(_ * _)
  }

scala>val input = List(3, 5, 7, 11)

scala> input.scanLeft(0)(_+_)

res0: List[Int] = List(0, 3, 8, 15, 26)
  1. segmentLength
    def segmentLength(p: (T) ⇒ Boolean, from: Int): Int
    从序列的 from 处开始向后查找,所有满足 p 的连续元素的长度
scala> arr.segmentLength(_<500,1)
res59: Int = 2

scala> arr
res60: Array[Int] = Array(1, 345, 65, 787, 98)

  1. seq
    def seq: collection.mutable.IndexedSeq[T]
    产生一个引用当前序列的 sequential 视图
scala> arr
res60: Array[Int] = Array(1, 345, 65, 787, 98)

scala> arr.seq
res61: scala.collection.mutable.IndexedSeq[Int] = WrappedArray(1, 345, 65, 787, 98)

  1. size
    def size: Int
    序列元素个数,同 length
scala> arr.size
res62: Int = 5

  1. slice
    def slice(from: Int, until: Int): Array[T]
    取出当前序列中,from 到 until 之间的片段
scala> arr.slice(1,4)
res63: Array[Int] = Array(345, 65, 787)

scala> arr
res64: Array[Int] = Array(1, 345, 65, 787, 98)

  1. sliding
    def sliding(size: Int): collection.Iterator[Array[T]]
    从第一个元素开始,每个元素和它后面的 size - 1 个元素组成一个数组,最终组成一个新的集合返回,当剩余元素不够 size 数,则停止
scala> arr
res68: Array[Int] = Array(1, 345, 65, 787, 98)

scala> arr.sliding(3).foreach(x=>println(x.mkString(",")))
1,345,65
345,65,787
65,787,98

def sliding(size: Int, step: Int): collection.Iterator[Array[T]]
从第一个元素开始,每个元素和它后面的 size - 1 个元素组成一个数组,最终组成一个新的集合返回,当剩余元素不够 size 数,则停止
该方法,可以设置步进 step,第一个元素组合完后,下一个从 上一个元素位置+step后的位置处的元素开始

scala> arr
res68: Array[Int] = Array(1, 345, 65, 787, 98)

scala> arr.sliding(3,3).foreach(x=>println(x.mkString(",")))
1,345,65
787,98
//可以加步长 记一次之后跳步长接着计数
scala> arr
res70: Array[Int] = Array(1, 345, 65, 787, 98)

scala> arr.sliding(3,2).foreach(x=>println(x.mkString(",")))
1,345,65

  1. sortBy
    def sortBy[B](f: (T) ⇒ B)(implicit ord: math.Ordering[B]): Array[T]
    按指定的排序规则排序
scala> arr.sortBy(x=>0-x)
res74: Array[Int] = Array(787, 345, 98, 65, 1)

scala> arr
res75: Array[Int] = Array(1, 345, 65, 787, 98)

  1. sortWith
    def sortWith(lt: (T, T) ⇒ Boolean): Array[T]
    自定义排序方法 lt
scala> val arr = Array("hello","world","are")
arr: Array[String] = Array(hello, world, are)

scala> arr.sortBy(x=>x)
res0: Array[String] = Array(are, hello, world)

scala> def mycomp(x:Any,y:Any):Boolean ={
     |   x+"" > y+""
     | }
mycomp: (x: Any, y: Any)Boolean

scala> arr1.sortWith(mycomp)
res2: Array[Any] = Array(world, hello, are, abc, 20)

  1. sorted
    def sorted[B >: A](implicit ord: math.Ordering[B]): Array[T]
    使用默认的排序规则对序列排序
   val a = Array(3,2,1,4,5)
    val b = a.sorted    
    println(b.mkString(","))    // 1,2,3,4,5

  1. 重点: span
    def span(p: (T) ⇒ Boolean): (Array[T], Array[T])
    分割序列为两个集合,从第一个元素开始,直到找到第一个不满足条件的元素止,之前的元素放到第一个集合,其它的放到第二个集合
scala> arr1
res9: Array[Any] = Array(hello, world, are, 20, abc)

scala> arr1.span(_.isInstanceOf[String])
res8: (Array[Any], Array[Any]) = (Array(hello, world, are),Array(20, abc))
//当碰到不满足的开始 后面所有的都放到另一个数组

  1. 重点: splitAt
    def splitAt(n: Int): (Array[T], Array[T])
    从指定位置开始,把序列拆分成两个集合
scala> arr1
res9: Array[Any] = Array(hello, world, are, 20, abc)

scala> arr1.splitAt(3)
res10: (Array[Any], Array[Any]) = (Array(hello, world, are),Array(20, abc))

  1. startsWith
    def startsWith[B](that: GenSeq[B], offset: Int): Boolean
    从指定偏移处,是否以某个序列开始
    def startsWith[B](that: GenSeq[B]): Boolean
    是否以某个序列开始
scala> arr1
res15: Array[Any] = Array(hello, world, are, 20, abc)

scala> val t1 = Array("world","are")
t1: Array[String] = Array(world, are)

scala> arr1.startsWith(t1)
res13: Boolean = false

scala> arr1.startsWith(t1,1)
res14: Boolean = true

  1. stringPrefix
    def stringPrefix: String
    返回 toString 结果的前缀
scala> "abcd".stringPrefix
res19: String = String

  1. subSequence
    def subSequence(start: Int, end: Int): CharSequence
    返回 start 和 end 间的字符序列
scala>     val chars = Array('a','b','c','d')
chars: Array[Char] = Array(a, b, c, d)

scala>     val b = chars.subSequence(1,3)
b: CharSequence = bc

  1. sum
    def sum: A
    序列求和,元素需为Numeric[T]类型
	val a = Array(1,2,3,4,5)
    val b = a.sum       //  15

  1. tail
    def tail: Array[T]
    返回除了当前序列第一个元素的其它元素组成的序列
  val a = Array(1,2,3,4,5)
    val b = a.tail      //  2,3,4,5

  1. 重点: take
    def take(n: Int): Array[T]
    返回当前序列中前 n 个元素组成的序列
scala> arr1.take(3)
res25: Array[Any] = Array(hello, world, are)

scala> arr1
res26: Array[Any] = Array(hello, world, are, 20, abc)

  1. takeRight
    def takeRight(n: Int): Array[T]
    返回当前序列中,从右边开始,选择 n 个元素组成的序列
scala> arr1
res26: Array[Any] = Array(hello, world, are, 20, abc)

scala> arr1.takeRight(3)
res27: Array[Any] = Array(are, 20, abc)

  1. takeWhile
    def takeWhile(p: (T) ⇒ Boolean): Array[T]
    返回当前序列中,从第一个元素开始,满足条件的连续元素组成的序列
scala> val s1 = Array(1,2,3,4,10,20,30,40,5,6,7,8,50,60,70,80)
s1: Array[Int] = Array(1, 2, 3, 4, 10, 20, 30, 40, 5, 6, 7, 8, 50, 60, 70, 80)

scala> s1.takeWhile(_<10)
res2: Array[Int] = Array(1, 2, 3, 4)

转换类型

  1. toArray
    def toArray: Array[A]
    转换成 Array 类型
scala> val a = List(1,2,3)
a: List[Int] = List(1, 2, 3)

scala> a.toArray
res3: Array[Int] = Array(1, 2, 3)
  1. toBuffer
    def toBuffer[A1 >: A]: Buffer[A1]
    转换成 Buffer 类型 将不可变转变为可变
scala> val b = Array(1,2,3)
b: Array[Int] = Array(1, 2, 3)

scala> b.toBuffer
res5: scala.collection.mutable.Buffer[Int] = ArrayBuffer(1, 2, 3)
  1. toIndexedSeq
    def toIndexedSeq: collection.immutable.IndexedSeq[T]
    转换成 IndexedSeq 类型(序列)
scala> val b = Array(1,2,3)
b: Array[Int] = Array(1, 2, 3)

scala> b.toIndexedSeq
res6: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 2, 3)
  1. toIterable
    def toIterable: collection.Iterable[T]
    转换成可迭代的类型
scala> val b = Array(1,2,3)
b: Array[Int] = Array(1, 2, 3)

scala> b.toIterable
res8: Iterable[Int] = WrappedArray(1, 2, 3)
  1. toList
    def toList: List[T]
    转换为 List 类型
scala> val b = Array(1,2,3)
b: Array[Int] = Array(1, 2, 3)

scala> b.toList
res7: List[Int] = List(1, 2, 3)
  1. toMap
    def toMap[T, U]: Map[T, U]
    转换为 Map 类型,需要被转化序列中包含的元素时 Tuple2 类型数据
    val chars = Array(("a","b"),("c","d"),("e","f"))
    val b = chars.toMap
	println(b)      //Map(a -> b, c -> d, e -> f)

  1. toSeq
    def toSeq: collection.Seq[T]
    转换为Seq 类型
scala> val b = Array(1,2,3)
b: Array[Int] = Array(1, 2, 3)

scala> b.toSeq
res9: Seq[Int] = WrappedArray(1, 2, 3)
  1. toSet
    def toSet[B >: A]: Set[B]
    转换为Set 类型
scala> val b = Array(1,2,3)
b: Array[Int] = Array(1, 2, 3)

scala> b.toSet
res10: scala.collection.immutable.Set[Int] = Set(1, 2, 3)
  1. toStream
    def toStream: collection.immutable.Stream[T]
    转换为Stream 类型
scala> val b = Array(1,2,3)
b: Array[Int] = Array(1, 2, 3)

scala> b.toStream
res11: scala.collection.immutable.Stream[Int] = Stream(1, ?)
  1. toVector
    def toVector: Vector[T]
    转换为Vector 类型
scala> val b = Array(1,2,3)
b: Array[Int] = Array(1, 2, 3)

scala> b.toVector
res12: Vector[Int] = Vector(1, 2, 3)
  1. transpose
    def transpose[U](implicit asArray: (T) ⇒ Array[U]): Array[Array[U]]
    矩阵转换,二维数组行列转换
scala> val ar = Array(Array(3,4,5),Array(7,8,9),Array(10,11,12))
ar: Array[Array[Int]] = Array(Array(3, 4, 5), Array(7, 8, 9), Array(10, 11, 12))

scala> ar.transpose
res37: Array[Array[Int]] = Array(Array(3, 7, 10), Array(4, 8, 11), Array(5, 9, 12))

  1. union
    def union(that: collection.Seq[T]): Array[T]
    联合两个序列,同操作符 ++
scala> val b = Array(1,2,3)
b: Array[Int] = Array(1, 2, 3)

scala> val c = Array(4,5,6)
c: Array[Int] = Array(4, 5, 6)

scala> val d = b.union(c)
d: Array[Int] = Array(1, 2, 3, 4, 5, 6)
  1. unzip
    def unzip[T1, T2](implicit asPair: (T) ⇒ (T1, T2), ct1: ClassTag[T1], ct2: ClassTag[T2]): (Array[T1], Array[T2])
    将含有两个元素的数组,第一个元素取出组成一个序列,第二个元素组成一个序列
scala> val arr = Array((1,2),(3,4),(5,6),(7,8))
arr: Array[(Int, Int)] = Array((1,2), (3,4), (5,6), (7,8))

scala> arr.unzip
res15: (Array[Int], Array[Int]) = (Array(1, 3, 5, 7),Array(2, 4, 6, 8))

scala> val arr1 = Array((1,2,3),(4,5,6),(7,8,9))
arr1: Array[(Int, Int, Int)] = Array((1,2,3), (4,5,6), (7,8,9))

scala> arr1.unzip
<console>:13: error: No implicit view available from (Int, Int, Int) => (T1, T2).
       arr1.unzip

//注意子元素只能有两个元素 超过2个或者1个都不能使用这个方法 
  1. unzip3
    def unzip3[T1, T2, T3](implicit asTriple: (T) ⇒ (T1, T2, T3), ct1: ClassTag[T1], ct2: ClassTag[T2], ct3: ClassTag[T3]): (Array[T1], Array[T2], Array[T3])
    将含有三个元素的三个数组,第一个元素取出组成一个序列,第二个元素组成一个序列,第三个元素组成一个序列
scala> val arr1 = Array((1,2,3),(4,5,6),(7,8,9))
arr1: Array[(Int, Int, Int)] = Array((1,2,3), (4,5,6), (7,8,9))

scala> arr1.unzip
<console>:13: error: No implicit view available from (Int, Int, Int) => (T1, T2).
       arr1.unzip
            ^

scala> arr1.unzip3
res17: (Array[Int], Array[Int], Array[Int]) = (Array(1, 4, 7),Array(2, 5, 8),Array(3, 6, 9))

//三个元素要unzip时就要用unzip3
  1. update
    def update(i: Int, x: T): Unit
    将序列中 i 索引处的元素更新为 x
scala> arr
res18: Array[(Int, Int)] = Array((1,2), (3,4), (5,6), (7,8))

scala> arr.update(1,(9,10))

scala> arr
res20: Array[(Int, Int)] = Array((1,2), (9,10), (5,6), (7,8))
  1. updated
    def updated(index: Int, elem: A): Array[A]
    将序列中 i 索引处的元素更新为 x ,并返回替换后的数组

scala> arr
res22: Array[(Int, Int)] = Array((1,2), (3,4), (5,6), (7,8))

scala> arr.updated(1,(9,10))
res24: Array[(Int, Int)] = Array((1,2), (9,10), (5,6), (7,8))

scala> arr
res25: Array[(Int, Int)] = Array((1,2), (3,4), (5,6), (7,8))
//不改变原数组的值 可以用新的数组来接这个值
  1. view
    def view(from: Int, until: Int): IndexedSeqView[T, Array[T]]
    返回 from 到 until 间的序列,不包括 until 处的元素
scala> arr1
res43: Array[Any] = Array(hello, world, are, 20, abc)

scala> arr1.view(1,3)
res48: scala.collection.mutable.IndexedSeqView[Any,Array[Any]] = SeqViewS(...)

scala> arr1.view(1,3).foreach(x=>println(x))
world
are

  1. withFilter
    def withFilter(p: (T) ⇒ Boolean): FilterMonadic[T, Array[T]]
    根据条件 p 过滤元素
scala> val a = Array(1,2,3,4,5)
a: Array[Int] = Array(1, 2, 3, 4, 5)


scala> a.withFilter(_>3).map(x=>x)
res31: Array[Int] = Array(4, 5)
  1. zip
    def zip[B](that: GenIterable[B]): Array[(A, B)]
    将两个序列对应位置上的元素组成一个pair序列 和unzip相对
scala> t1
res51: Array[String] = Array(world, are)

scala> t2
res52: Array[Any] = Array(are, 20)

scala> t1.zip(t2)
res53: Array[(String, Any)] = Array((world,are), (are,20))

scala> val t3 = Array(1,2,3,4,5)
t3: Array[Int] = Array(1, 2, 3, 4, 5)

scala> t3.zip(t1)
res54: Array[(Int, String)] = Array((1,world), (2,are))

  1. zipAll
    def zipAll[B](that: collection.Iterable[B], thisElem: A, thatElem: B): Array[(A, B)]
    zipAll 函数和上面的zip函数类似,但是如果其中一个元素个数比较少,那么将用默认的元素填充
scala> val s1 = Array(1,2,3,4,5)
s1: Array[Int] = Array(1, 2, 3, 4, 5)

scala> val s2 = Array("a","b","c","d")
s2: Array[String] = Array(a, b, c, d)

scala> s1.zipAll(s2,"f","g")
res34: Array[(Any, String)] = Array((1,a), (2,b), (3,c), (4,d), (5,g))
  1. zipWithIndex
    def zipWithIndex: Array[(A, Int)]
    给集合按顺序添加索引构成元组
//使用zipWithIndex和counter来打印带有计数器的集合元素
scala> val days = Array("Sunday", "Monday", "Tuesday", "Wednesday","Thursday", "Friday", "Saturday")
days: Array[String] = Array(Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday)

scala> days.zipWithIndex.foreach{case(day,count) => println(s"$count is $day")}
0 is Sunday
1 is Monday
2 is Tuesday
3 is Wednesday
4 is Thursday
5 is Friday
6 is Saturday
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值