Scala基础

Scala简介

  • Scala源自Java
    Scala构建在JVM之上
    Scala与Java兼容、互通
  • Scala的优势
    多范式编程:面向对象编程、函数式编程
    表达能力强、代码精简
  • 大数据与Scala
    Spark采用Scala语言设计
    • 提供的API更加优雅
      基于JVM的语言更融入Hadoop生态圈

安装scala

#################### 安装Scala ######################
安装Scala,版本要和idea相同
https://www.scala-lang.org/download
要求JDK环境
idea中配置scala,安装包放进idea中

scala开发环境

在这里插入图片描述
启用装好的scala编译器
在这里插入图片描述
选择与idea版本对应的scala的解压包
在这里插入图片描述
在这里插入图片描述
新建项目中出现scala说明安装成功
在这里插入图片描述

scala交互式编程

cmd
color f0
1+1
res0+12
main方法写对象里,对象object
args:Array[String]   参数
Unit=   返回值类型
public static void main(String []args){}
def main(args:Array[String]):Unit={}

scala初体验

scala> object MyHello{
     |   def main(args:Array[String]):Unit={
     |     println("Hello,world");
     |   }
     | }
MyHello.main(null)
Hello,world

Scala概述

  • 面向对象特征
    每个值都是对象
    对象的数据类型和行为由类(class)和特征(Trait,类似于interface)描述
    利用特征实现混入式多重继承
  • 函数式编程
    每个函数都是一个值
    支持高阶函数、柯里化(currying)、样例化(case class)及模式匹配…
  • scala是静态类型语言
  • 扩展性

Scala变量与常量

变量

复制后可以改变,生命周期中可以被多次赋值
var 变量名称:类型=xxx

定义变量:var c=20     c: Int = 20
		  var c="abc"    c: String = abc
c=40 
<console>:15: error: type mismatch;
 found   : Int(40)
 required: String
       c=40
c="40"    c: String = 40

一般无需显示指定类型,Scala编译器会自动推断出类型

常量

val 常量名称:类型=xxx

val k=50    k: Int = 50
k=60 
<console>:15: error: reassignment to val
       k=60 
错,常量不可更改  
k    res16: Int = 50

类型别名

type关键字
type 类型别名=类型

type T=String     defined type alias T
val name:T="jason"      name: T = jason

Scala数据类型

Scala与Java有着相同的原始数据类型
在这里插入图片描述

Scala数据类型层次结构

Any:所有类型的超类(顶级类型)
AnyVal:表示值类型的超类
AnyRef:表示引用类型的超类,对应java.lang.Object
Unit:表示无值,类似于Java中的void
Nothing:所有类型的子类
Null:表示null或空引用
在这里插入图片描述

Scala循环控制

while

scala> var num:Int=0;
num: Int = 0

scala> while(num<100){
     |     print(num+" ");
     |     num=num+1;
     | }
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
scala>

do…while

scala> var num:Int=0;
num: Int = 0

scala> do {
     |     print(num+" ");
     |     num=num+5;
     | }while(num<200);
0 5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95 100 105 110 115 120 125 130 135 140 145 150 155 160 165 170 175 180 185 190 195
scala>

for循环

“i to j”或者"i until j"均表示创建一个区间Range
to前后都含

scala> var i=0;
i: Int = 0

scala> for(i:Int <- 0 to 10) {
     |     print(i+" ");
     | }
0 1 2 3 4 5 6 7 8 9 10

until前含后不含

scala> var i=0;
i: Int = 0

scala> for(i:Int <- 0 until 10) {
     |     print(i+" ");
     | }
0 1 2 3 4 5 6 7 8 9

中断

break

scala> import util.control.Breaks._
import util.control.Breaks._

scala> for (k:Int <- 1 to 10) {
     |     if(k==5) {
     |         break;
     |     }
     |     print(k+" ");
     | }
1 2 3 4 scala.util.control.BreakControl

跳breakable方法实现continue

scala> import util.control.Breaks._
import util.control.Breaks._

scala> for(k:Int <- 1 to 10) {
     |     breakable {
     |         if(k==5) {
     |             break;
     |         }
     |         print(k+" ");
     |     }
     | }
1 2 3 4 6 7 8 9 10

for循环过滤

val num=10;
scala> for(i:Int <- 1 to num;if i%2==0;if i>5) {
     |     println(i*100);
     | }
600
800
1000

for循环返回值

for循环中的yield会把当前的元素记下来,保存在集合中,循环结束后将返回该集合

scala> var arr=for(k:Int <- 1 to 10) yield k;
arr: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

scala> for(a <- arr) {
     |     print(a+" ");
     | }
1 2 3 4 5 6 7 8 9 10

// 遍历
scala> for(a:Int <- arr) {
     |     print(a+" ");
     | }
1 2 3 4 5 6 7 8 9 10

使用scala语句实现
0+6=6
1+5=6
2+4=6
3+3=6
4+2=6
5+1=6
6+0=6

scala> for(i:Int <- 0 to 6) {
     |      println(i + "+" + (6-i) + "=" + 6);
     | }
0+6=6
1+5=6
2+4=6
3+3=6
4+2=6
5+1=6
6+0=6

// 输出
*
**





scala> var star="*";
star: String = *

scala> for(k:Int <- 1 to 5) {
     |     println(star);
     |     star += "*";
     | }
*
**
***
****
*****

Scala数组

存储固定大小的元素
数组索引从0开始
泛型使用方括号
数据元素访问使用圆括号
调用Array的伴生对象中的apply()返回Array实例

//数组创建方式一
scala> var al:Array[String] = new Array[String](3);
al: Array[String] = Array(null, null, null)

scala> al(0)="Jason";
scala> al(1)="Marie";
scala> al(2)="Jimmy";

scala> for(a <- al) {
     |    print(a+",");
     | }
Jason,Marie,Jimmy
scala>

//数组创建方式二
scala> var a2=Array("Jason","Marie","Jimmy");
a2: Array[String] = Array(Jason, Marie, Jimmy)

//数据创建方式三:区间数组
1-10表示范围,2表示步长
scala> var a3=Array.range(1,10,2);
a3: Array[Int] = Array(1, 3, 5, 7, 9)

Scala元组

可以包含不同类型的元素
最多支持22个元素(Tuple1~Tuple22)
使用下划线“_”访问元素,“_1”表示第一个元素

// 元祖声明方式一
scala> var tp1=("Mike","123 ABC street",58)
tp1: (String, String, Int) = (Mike,123 ABC street,58)

scala> println(tp1._1);
Mike
scala> println(tp1._2);
123 ABC street

//迭代元组
scala> tp1.productIterator.foreach{i=>println("Value="+i)}
Value=Mike
Value=123 ABC street
Value=58

//元组声明方式二
scala> var tp2=new Tuple3("Mike","123 ABC street",58);
tp2: (String, String, Int) = (Mike,123 ABC street,58)

//元组声明方式三
scala> def mike="Mike"->5
mike: (String, Int)
//输出scala.Tuple2
scala> mike.getClass
res42: Class[_ <: (String, Int)] = class scala.Tuple2
//将元组元素依次赋给三个变量
scala> val(name,address,age)=tp1
name: String = Mike
address: String = 123 ABC street
age: Int = 58

scala> println(name)
Mike
scala> println(address)
123 ABC street

// 二元元祖:对wordcount比较有用
scala> val k="eee"->5
k: (String, Int) = (eee,5)

// 嵌套二元元祖
scala> val k="eee"->5->6
k: ((String, Int), Int) = ((eee,5),6)

// 只要结构一样,就能取出对应值   解构语法
scala> val ((a,b),c) = k
a: String = eee
b: Int = 5
c: Int = 6

元祖的函数

scala> val tp1 =("zhangsan","ls",50,12.5);
tp1: (String, String, Int, Double) = (zhangsan,ls,50,12.5)

scala> tp1.productIterator.foreach{i=>println(i)}
zhangsan
ls
50
12.5

scala> tp1.
_1   _3   canEqual   equals     productArity     productIterator   toString
_2   _4   copy       hashCode   productElement   productPrefix

scala> tp1.productIterator.
++                corresponds   foldRight            max         reduceLeft          span           toSeq
/:                count         forall               maxBy       reduceLeftOption    sum            toSet
:\                drop          foreach              min         reduceOption        take           toStream
GroupedIterator   dropWhile     grouped              minBy       reduceRight         takeWhile      toString
addString         duplicate     hasDefiniteSize      mkString    reduceRightOption   to             toTraversable
aggregate         exists        hasNext              next        sameElements        toArray        toVector
buffered          filter        indexOf              nonEmpty    scanLeft            toBuffer       withFilter
collect           filterNot     indexWhere           padTo       scanRight           toIndexedSeq   zip
collectFirst      find          isEmpty              partition   seq                 toIterable     zipAll
contains          flatMap       isTraversableAgain   patch       size                toIterator     zipWithIndex
copyToArray       fold          length               product     slice               toList
copyToBuffer      foldLeft      map                  reduce      sliding             toMap

Scala集合

Seq:序列,元素按顺序排列
Set:集合,元素不重复
Map:映射,键值对集合
在这里插入图片描述

不可变集合

scala.clooection.immutable,默认Scala选择不可变集合
在这里插入图片描述
在这里插入图片描述

可变集合

可以修改、添加、或移除一个集合的元素
scala.collection.mutable
带buffer的都是可变的
在这里插入图片描述

常用集合

在这里插入图片描述

数组和集合的函数

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

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

scala> c ++ arr
res0: Array[Int] = Array(2, 3, 4, 67, 88, 1, 2, 3, 4, 5, 6)

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

// 取决于后面的数据类型
scala> a ++: arr
res1: Array[Int] = Array(3, 4, 5, 1, 2, 3, 4, 5, 6)

scala> var k = 100
k: Int = 100

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

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

// 数据类型取决于:的方向
scala> k +: a
res5: List[Int] = List(100, 3, 4, 5)

// a当成方法来加
scala> c.++(a)
res6: Array[Int] = Array(2, 3, 4, 67, 88, 3, 4, 5)

scala> k
res7: Int = 100

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

// :方向代表集合的方向
scala> (100 /: a)(_+_)
res9: Int = 112

scala> (a :\ 100)(_+_)
res11: Int = 112

// 建立一个空字符串
scala> var str = new StringBuilder
str: StringBuilder =

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

scala> str
res13: StringBuilder = 345

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

scala> var str = ""
str: String = ""

scala> var str = new StringBuilder
str: StringBuilder =

scala> a.addString(str,"[",",","]")
res16: StringBuilder = [3,4,5]
addString用java来表示
public String addString(List lst, String start, String flag, String end) {
        StringBuffer sb = new StringBuffer();
        sb.append(start);
        for (Object o : lst) {
            sb.append(o+flag);
        }
        Pattern p = Pattern.compile(flag + "$");
        sb.append(end);
        sb = new StringBuffer(sb.toString().replaceFirst(flag+"$",""));
        return sb.toString();
    }

    public static void main(String[] args) {
        App app = new App();
        List lst = new ArrayList();
        lst.add(34);
        lst.add(23);
        lst.add(44);
        lst.add(5);
        lst.add("sdf");
        System.out.println(app.addString(lst,"[",",","]"));      // [34,23,44,5,sdf,]

// par并行集合,集合分散到多个节点上 scala并行集合 分治算法

在这里插入代码片scala> val c = Array(2,3,4,56,76,43,58)
c: Array[Int] = Array(2, 3, 4, 56, 76, 43, 58)

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

// canEqual是否可以相比   数组:万物皆可比
scala> c.canEqual(d)
res0: Boolean = true

scala> c.canEqual("aa")
res1: Boolean = true

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

scala> object myObj{}   对象
defined object myObj

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

scala> e.charAt(2)
res5: Char = c

scala> var e = Array('a','b','c')
e: Array[Char] = Array(a, b, c)

// 把c的指针同时指向e
scala> var e = c
e: Array[Int] = Array(2, 3, 4, 56, 76, 43, 58)

scala> c
res6: Array[Int] = Array(2, 3, 4, 56, 76, 43, 58)

scala> c(2)=44

scala> c
res8: Array[Int] = Array(2, 3, 44, 56, 76, 43, 58)

scala> e
res9: Array[Int] = Array(2, 3, 44, 56, 76, 43, 58)
// clone相当于复制
scala> var k = c.clone
k: Array[Int] = Array(2, 3, 44, 56, 76, 43, 58)

scala> c(2)=100

scala> c
res11: Array[Int] = Array(2, 3, 100, 56, 76, 43, 58)

scala> k
res12: Array[Int] = Array(2, 3, 44, 56, 76, 43, 58)

scala> var fun:PartialFunction[Int,Int]={
     |   case x => x+1
     | }
fun: PartialFunction[Int,Int] = <function1>

scala> c.collect(fun)
res13: Array[Int] = Array(3, 4, 101, 57, 77, 44, 59)

scala> var fun:PartialFunction[Int,Int]={
     |   case 3 => 13
     | }
fun: PartialFunction[Int,Int] = <function1>

scala> c.collect(fun)
res14: Array[Int] = Array(13)
// 偏函数:对不同的部分采用不同的处理方式
scala> val fun:PartialFunction[Int,Int]={
     |   case 3 => 13
     |   case y if y%2==0 => y+50
     |   case x => x
     | }
fun: PartialFunction[Int,Int] = <function1>

scala> c.collect(fun)
res15: Array[Int] = Array(52, 13, 150, 106, 126, 43, 108)

scala>  val fun:PartialFunction[Int,String]={
     |   case 3 => "xixi"
     |   case y if y%2==0 => "gg"
     |   case x => x+"ff"
     | }
fun: PartialFunction[Int,String] = <function1>

scala> c.collect(fun)
res16: Array[String] = Array(gg, xixi, gg, gg, gg, 43ff, gg)
scala> c.combinations(3)
res17: Iterator[Array[Int]] = non-empty iterator   // 迭代器就是一个指针,只能迭代一遍

scala> c
res18: Array[Int] = Array(2, 3, 100, 56, 76, 43, 58)
             
scala> var ee = c.combinations(3)
ee: Iterator[Array[Int]] = non-empty iterator                            ^

scala> ee.foreach(x=>println(x))
[I@4865434e
[I@3c6e407
[I@287dde94
[I@2f650dae
[I@4df8443f
[I@79aa675b
[I@3fe59f84
[I@38eafdab
[I@373c8f35
[I@1d86b636
[I@e0c03bd
[I@61e4a072
[I@32f2de5c
[I@1a6df932
[I@74120029
[I@3031d9e9
[I@1415f18d
[I@61c42e54
[I@533690d
[I@3bf306d3
[I@5101b9
[I@40273969
[I@5ec25b61
[I@7da40bf4
[I@75708130
[I@c651286
[I@40304938
[I@1d160161
[I@6c9e7af2
[I@48cbb4c5
[I@af04d6d
[I@2740585b
[I@3816efab
[I@2d6e09f0
[I@257da215

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

scala> ee.foreach(x=>println(x.mkString(",")))
2,3,100
2,3,56
2,3,76
2,3,43
2,3,58
2,100,56
2,100,76
2,100,43
2,100,58
2,56,76
2,56,43
2,56,58
2,76,43
2,76,58
2,43,58
3,100,56
3,100,76
3,100,43
3,100,58
3,56,76
3,56,43
3,56,58
3,76,43
3,76,58
3,43,58
100,56,76
100,56,43
100,56,58
100,76,43
100,76,58
100,43,58
56,76,43
56,76,58
56,43,58
76,43,58
// 是否包含元素
scala> c.contains(50)
res23: Boolean = false

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

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

// 是否包含数组
scala> c.containsSlice(d)
res25: Boolean = false

// drop丢弃元素
scala> d.drop(2)
res26: Array[Int] = Array(50)

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

scala> d.dropRight(2)
res28: Array[Int] = Array(23)

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

scala> val a =Array(0,0,0,0,0,0,0)
a: Array[Int] = Array(0, 0, 0, 0, 0, 0, 0)

scala> c
res31: Array[Int] = Array(2, 3, 100, 56, 76, 43, 58)

scala> a
res32: Array[Int] = Array(0, 0, 0, 0, 0, 0, 0)
// 把c拷贝到a,从a的第二个位置开始考
scala> c.copyToArray(a,2)

scala> a
res34: Array[Int] = Array(0, 0, 2, 3, 100, 56, 76)
scala> import scala.
#::                              Product14
+:                               Product15
:+                               Product16
::                               Product17
AbstractMethodError              Product18
Any                              Product19
AnyRef                           Product2
AnyVal                           Product20
AnyValCompanion                  Product21
App                              Product22
Array                            Product3
ArrayIndexOutOfBoundsException   Product4
BigDecimal                       Product5
BigInt                           Product6
Boolean                          Product7
BufferedIterator                 Product8
Byte                             Product9
Char                             Proxy
ClassCastException               Range
Cloneable                        Responder
Console                          Right
DelayedInit                      RuntimeException
DeprecatedConsole                ScalaReflectionException
DeprecatedPredef                 Seq
Double                           SerialVersionUID
Dynamic                          Serializable
Either                           Short
Enumeration                      Singleton
Equals                           Some
Equiv                            Specializable
Error                            Stream
Exception                        StringBuilder
FallbackArrayBuilding            StringContext
Float                            StringIndexOutOfBoundsException
Fractional                       Symbol
Function                         Throwable
Function0                        Traversable
Function1                        TraversableOnce
Function10                       Tuple1
Function11                       Tuple10
Function12                       Tuple11
Function13                       Tuple12
Function14                       Tuple13
Function15                       Tuple14
Function16                       Tuple15
Function17                       Tuple16
Function18                       Tuple17
Function19                       Tuple18
Function2                        Tuple19
Function20                       Tuple2
Function21                       Tuple20
Function22                       Tuple21
Function3                        Tuple22
Function4                        Tuple3
Function5                        Tuple4
Function6                        Tuple5
Function7                        Tuple6
Function8                        Tuple7
Function9                        Tuple8
IllegalArgumentException         Tuple9
Immutable                        UninitializedError
IndexOutOfBoundsException        UninitializedFieldError
IndexedSeq                       UniquenessCache
Int                              Unit
Integral                         UnsupportedOperationException
InterruptedException             Vector
Iterable                         actors
Iterator                         annotation
Left                             beans
List                             collection
Long                             compat
LowPriorityImplicits             concurrent
MatchError                       deprecated
Mutable                          deprecatedName
Nil                              inline
NoSuchElementException           io
None                             language
NotImplementedError              languageFeature
NotNull                          math
Nothing                          native
Null                             noinline
NullPointerException             package
NumberFormatException            ref
Numeric                          reflect
Option                           remote
Ordered                          runtime
Ordering                         specialized
PartialFunction                  swing
PartialOrdering                  sys
PartiallyOrdered                 text
Predef                           throws
Product                          tools
Product1                         transient
Product10                        unchecked
Product11                        util
Product12                        volatile
Product13                        xml

scala> import scala.util.
DynamicVariable   MurmurHash        Right     continuations   parsing
Either            Properties        Sorting   control
Failure           PropertiesTrait   Success   hashing
Left              Random            Try       matching

scala> import scala.collection.mutable.Array
ArrayBuffer   ArrayBuilder   ArrayLike   ArrayOps   ArraySeq   ArrayStack

scala> import scala.collection.mutable.ArrayBu
ArrayBuffer   ArrayBuilder

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> var a:ArrayBuffer[Int] = ArrayBuffer()
a: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer()

scala> c.copyToBuffer(a)

scala> a
res37: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(2, 3, 100, 56, 76, 43, 58)
// 比较两者是否相同
scala> c.corresponds(a)(_==_)
res38: Boolean = true

scala> a.re
readOnly     reduceLeftOption   reduceRightOption   repr      reverseIterator
reduce       reduceOption       reduceToSize        result    reverseMap
reduceLeft   reduceRight        remove              reverse

scala> a.remove(3)
res39: Int = 56

scala> a
res40: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(2, 3, 100, 76, 43, 58)

scala> c.corresponds(a)(_==_)
res41: Boolean = false
// 统计偶数个数
scala> c.count(p=>p%2==0)
res42: Int = 5

scala> c:+23
res46: Array[Int] = Array(2, 3, 100, 56, 76, 43, 58, 23)

scala> c
res43: Array[Int] = Array(2, 3, 100, 56, 76, 43, 58)

scala> var c =Array(2,3,100,56,76,42,58)
c: Array[Int] = Array(2, 3, 100, 56, 76, 42, 58)

scala> c=c:+2
c: Array[Int] = [I@261b4fa

scala> c.distinct
res49: Array[Int] = Array(2, 3, 100, 56, 76, 42, 58)

scala> c.drop
drop   dropRight   dropWhile

scala> c.dropWhile(p=>p%2==0)
res50: Array[Int] = Array(3, 100, 56, 76, 42, 58, 2)

scala> a
res51: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(2, 3, 100, 76, 43, 58)

scala> a.drop
drop   dropRight   dropWhile

scala> a.dropWhile(p=>p%2==0)
res52: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(3, 100, 76, 43, 58)
// 删除直到碰到第一个不满足条件的元素为止
scala> val a =Array(3,2,3,4)
a: Array[Int] = Array(3, 2, 3, 4)

scala> val c = a.dropWhile({x:Int => x>2})
c: Array[Int] = Array(2, 3, 4)

scala> println(c.mkString(","))
2,3,4

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

scala> a
res56: Array[Int] = Array(3, 2, 3, 4)
// a是否以c结尾
scala> a.endsWith(c)
res54: Boolean = true

scala> a.st
startsWith   stringPrefix

// a是否以c开头
scala> a.startsWith(c)
res55: Boolean = false

// a里元素是否存在大于5的
scala> a.exists(p=>p>5)
res57: Boolean = false
// 过滤
scala> a.filter
filter   filterNot

scala> a.filter(p=>p%2==0)   过滤偶数
res58: Array[Int] = Array(2, 4)
// 判断是否为偶数的函数
scala> def myfun(p:Int):Boolean={
     |   p%2==0
     | }
myfun: (p: Int)Boolean

scala> a.filter(myfun)    // 函数作为参数传递给另一个函数:高阶函数
res60: Array[Int] = Array(2, 4)

scala> a.filterNot(myfun)     // 反过滤
res61: Array[Int] = Array(3, 3)

scala> a.find(x=>x==2)
res62: Option[Int] = Some(2)   // 返回some类型的数组  代表找到了之后放入some数组里

scala> a.find(x=>x==2).g
genericBuilder   get   getClass   getOrElse   groupBy   grouped

scala> a.find(x=>x==2).get    // some类型拿取的方法是get
res63: Int = 2
scala> val c = Array(4,5,6)
c: Array[Int] = Array(4, 5, 6)

scala> c.flat
flatMap   flatten

scala> c.map(x=>(1 to x))   返回从1到x的数组
res65: 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
res66: Array[Int] = Array(1, 2, 3, 4, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 6)
	   
scala> c.flatMap(x=>(1 to x))    // flatMap = flatten(扁平化)+map  返回两层数组  先map再flatten
res64: Array[Int] = Array(1, 2, 3, 4, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 6)    // 扁平化
柯里化:把接受多个参数变成接受单个参数的函数链  
public void eee(String s,String y)...
def eee(s:String)(y:String)...

var ee = function(k){alert(k);}
var ff = function(fun){return fun;}
ff(ee)(10); => 10        // 柯里化

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

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

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

scala> c.fold(5)(nyfun)
res69: Int = 20

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

scala> def seqno(m:Int,n:Int): Int ={
     | 		val s = "seq_exp=%d+%d"
     | 		println(s.format(m,n))
     | 		return m+n
     | }
seqno: (m: Int, n: Int)Int

scala> def combine(m:Int,n:Int): Int ={
     |     val s = "com_exp=%d+%d"
     |     println(s.format(m,n))
     |     return m+n
     | }
combine: (m: Int, n: Int)Int

scala> val b = a.fold(5)(seqno)
seq_exp=5+1
seq_exp=6+2
seq_exp=8+3
seq_exp=11+4
b: Int = 15

scala> val c = a.par.aggregate(5)(seqno,combine)
seq_exp=5+3
seq_exp=5+4
seq_exp=5+2
seq_exp=5+1
com_exp=6+7
com_exp=8+9
com_exp=13+17
c: Int = 30

scala> val c = a.par.aggregate(5)(seqno,combine)
seq_exp=5+1
seq_exp=5+3
seq_exp=5+4
seq_exp=5+2
com_exp=8+9
com_exp=6+7
com_exp=13+17
c: Int = 30

scala> val c = a.par.aggregate(5)(seqno,combine)
seq_exp=5+1
seq_exp=5+3
seq_exp=5+4
seq_exp=5+2
com_exp=8+9
com_exp=6+7
com_exp=13+17
c: Int = 30
scala> val k =Array(34,55,776,8,67)
k: Array[Int] = Array(34, 55, 776, 8, 67)

scala> var a = 21
a: Int = 21

scala> var a = Array(1,2,3)
a: Array[Int] = Array(1, 2, 3)

scala> k.g
genericBuilder   getClass   groupBy   grouped

scala> k.group
groupBy   grouped

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

scala> k.grouped(3)
res72: Iterator[Array[Int]] = non-empty iterator

scala> k.grouped(3).foreach(x=>println(x))
[I@6c2ff925
[I@7985c7ed

scala> k.grouped(3).foreach(x=>println(x.mkString(",")))
34,55,776
8,67
scala> k.head    // 返回序列中的第一个元素
res75: Int = 34

scala> k.tail    // 返回去头
res76: Array[Int] = Array(55, 776, 8, 67)

scala> k.last
res77: Int = 67

scala> var lst = ArrayBuffer()
lst: scala.collection.mutable.ArrayBuffer[Nothing] = ArrayBuffer()

scala> lst.headOption
res80: Option[Nothing] = None
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))   // 返回下标
res81: Int = 3

scala> a.indexWhere(p=>p>10)
res82: Int = 10
scala> a.init    // 去尾
res83: scala.collection.immutable.Range = Range(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19)

// 依次做init操作,直至为空
scala> val a = Array(1,2,3,4,5)
a: Array[Int] = Array(1, 2, 3, 4, 5)

scala> val b = a.inits.toList
b: List[Array[Int]] = List(Array(1, 2, 3, 4, 5), Array(1, 2, 3, 4), Array(1, 2, 3), Array(1, 2), Array(1), Array())

scala> for(i <- 1 to b.length) {
     | 		val s = "第%d个值:%s"
     | 		println(s.format(i,b(i-1).mkString(",")))
     | }1个值:1,2,3,4,52个值:1,2,3,43个值:1,2,34个值:1,25个值:16个值:
// 取两个集合的交集
scala> val a =Array(1,2,2,3,4,5)
a: Array[Int] = Array(1, 2, 2, 3, 4, 5)

scala> val b = Array(3,4,5)
b: Array[Int] = Array(3, 4, 5)

scala> val c = a.intersect(b)
c: Array[Int] = Array(3, 4, 5)
// 判断是否有20这个下标
scala> b.isDefinedAt(20)
res85: Boolean = false

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

scala> b.isEmpty
res86: Boolean = false

scala> import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.ArrayBuffer

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

scala> c.isEmpty
res87: Boolean = true
// 判断序列是否可以反复遍历,迭代器不可以反复遍历  isTraversableAgain
scala> val arr = Array(1,345,65,787,98)
arr: Array[Int] = Array(1, 345, 65, 787, 98)

scala> arr.isTraversableAgain
res57: Boolean = true

scala> arr.inits.isTraversableAgain
res58: Boolean = false

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

scala> arr.iterator.isTraversableAgain
res60: Boolean = false
// 迭代器的foreach方法,只有collection的集合才有迭代器
public static void main(String[] args){
	List lst = new ArrayList();
	lst.add(34);
	lst.add(24);
	lst.add(5);
	lst.add(44);
	lst.add("sdf");
	
	for(Iterator iterator = lst.iterator();iterator.hasNext();){
		sou(iterator.next());
	}	
}
// lengthCompare比较数组长度和给定的值的差
scala> arr.lengthCompare(3)
res61: Int = 2

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

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

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

scala> arr.lengthCompare(5)
res65: Int = 0
// 单词计数出现的次数
scala> val str = "hello mysql hello world"
str: String = hello mysql hello world

scala> str.split(" ")
res67: Array[String] = Array(hello, mysql, hello, world)

scala> str.split(" ").map(x => (x,1))
res68: Array[(String, Int)] = Array((hello,1), (mysql,1), (hello,1), (world,1))  // 元组类型的数组

// 按数组里元组的第一个元素即单词分组
scala> str.split(" ").map(x => (x,1)).groupBy(x => x._1)    
// world是键,Array((world,1))是值,值是数组,数组的长度就是出现的次数
res69: scala.collection.immutable.Map[String,Array[(String, Int)]] = 
	Map(world -> Array((world,1)), mysql -> Array((mysql,1)), hello -> Array((hello,1), (hello,1))) 

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

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

// 扁平化集合
scala> val c = List("hello world","hello hadoop","hadoop hive")
c: List[String] = List(hello world, hello hadoop, hadoop hive)

scala> c.map(_.split(" "))
res73: List[Array[String]] = List(Array(hello, world), Array(hello, hadoop), Array(hadoop, hive))

scala> c.map(_.split(" ")).flatten
res74: List[String] = List(hello, world, hello, hadoop, hadoop, hive)

scala> c.flatMap(_.split(" "))
res76: List[String] = List(hello, world, hello, hadoop, hadoop, hive)
// 找序列中的最大最小值,和第一个符合条件的值
scala> arr.max
res78: Int = 787

scala> arr.maxBy(_>456)
res79: Int = 787

scala> arr.min
res80: Int = 1

scala> arr.minBy(_>34)
res81: Int = 1

scala> a
res82: Array[String] = Array(hello, mysql, hello, world)

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

scala> arr.minBy(_<1)
res84: Int = 1

scala> arr.nonEmpty
res85: Boolean = true
// 特定位置补位
scala> arr.padTo(10,0)    // 补位
res86: Array[Int] = Array(1, 345, 65, 787, 98, 0, 0, 0, 0, 0)

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

// 批量替换
scala> val a1 = arr.padTo(10,0)
a1: Array[Int] = Array(1, 345, 65, 787, 98, 0, 0, 0, 0, 0)

scala> arr1.copyToArray(a1,5,3)

scala> a1
res88: Array[Int] = Array(1, 345, 65, 787, 98, 1, 2, 3, 0, 0)
scala> arr.partition(_%2 == 0)    // 奇偶分区
res89: (Array[Int], Array[Int]) = (Array(98),Array(1, 345, 65, 787))

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

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

scala> arr.patch(0,arr1,1)    // 批量替换
res92: Array[Int] = Array(1, 2, 3, 345, 65, 787, 98)
// 组合
scala> arr.combinations(3)
res93: Iterator[Array[Int]] = non-empty iterator

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

// 排列组合
scala> arr.permutations.toList
res95: 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.permutations.toList.length
res96: Int = 120

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

scala> arr1.permutations
res98: Iterator[Array[Int]] = non-empty iterator

scala> arr1.permutations.toList
res99: 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))

scala> arr1.permutations.to
to        toBuffer       toIterable   toList   toSeq   toStream   toTraversable
toArray   toIndexedSeq   toIterator   toMap    toSet   toString   toVector

scala> arr1.permutations.toSeq
res101: Seq[Array[Int]] = Stream([I@5011663b, ?)

scala> arr1.permutations.toSet
res102: scala.collection.immutable.Set[Array[Int]] = Set(Array(1, 3, 2), Array(1, 2, 3),   // 不可改变的
	Array(3, 2, 1), Array(2, 1, 3), Array(2, 3, 1), Array(3, 1, 2))
scala> arr.prefixLength(_<787)   // 前置小于787
res103: Int = 3

scala> (1 to 5).product  // 求积
res104: Int = 120

scala> (1 to 5).sum   // 求和
res105: Int = 15

scala> arr.reduce
reduce       reduceLeftOption   reduceRight
reduceLeft   reduceOption       reduceRightOption

scala> arr.reduce(_+_)   // 求和
res106: Int = 1296

scala> arr.reverse
reverse   reverseIterator   reverseMap

scala> arr.reverse    // 序列反转,java里的StringBuffer
res107: Array[Int] = Array(98, 787, 65, 345, 1)

scala> arr.reverseMap((_,1))  // 反转后作为键放入map
res108: Array[(Int, Int)] = Array((98,1), (787,1), (65,1), (345,1), (1,1))
scala> val arr2 = arr.clone
arr2: Array[Int] = Array(1, 345, 65, 787, 98)

scala> arr.sameElements(arr2)   // 比较是否相同
res109: Boolean = true

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

// 从第二位开始找找符合<500的连续元素的长度
scala> arr.segmentLength(_<500,1)  
res111: Int = 2

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

scala> arr.slice(1,4)
res113: Array[Int] = Array(345, 65, 787)

// 从第一个元素开始,每个元素和它后面的 size - 1 个元素组成一个数组,
// 最终组成一个新的集合返回,当剩余元素不够 size 数,则停止
scala> arr.sliding(3).foreach(x => println(x.mkString(",")))
1,345,65
345,65,787
65,787,98

// 第一次向后跳三位然后再取值,第二个3表示步长
scala> arr.sliding(3,3).foreach(x => println(x.mkString(",")))
1,345,65
787,98

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

scala> arr.sliding(3,4).foreach(x => println(x.mkString(",")))
1,345,65
98
scala> arr.sortBy(x => x)   // 默认升序
res118: Array[Int] = Array(1, 65, 98, 345, 787)

scala> arr.sortBy(x => 0-x)    // 降序
res119: Array[Int] = Array(787, 345, 98, 65, 1)
scala> val arr = Array("hello","world","are")
arr: Array[String] = Array(hello, world, are)

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

scala> var arr1 = arr:+20
arr1: Array[Any] = Array(hello, world, are, 20)

scala> var arr1 = arr:+20:+"abc"
arr1: Array[Any] = Array(hello, world, are, 20, abc)

scala> arr1.sortBy(x => x)
<console>:14: error: No implicit Ordering defined for Any.
       arr1.sortBy(x => x)

scala> arr1.map(x=>x+"")
res127: Array[String] = Array(hello, world, are, 20, abc)

scala> arr1.map(x=>x+"").sortWith(_.compareTo(_)>0)
res126: Array[String] = Array(world, hello, are, abc, 20)

scala> def mycomp(x:Any,y:Any):Boolean = {
     |     x.asInstanceOf[String] > y.asInstanceOf[String]
     | }
mycomp: (x: Any, y: Any)Boolean

scala> mycomp("abc",20)
java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
  at .mycomp(<console>:12)
  ... 32 elided

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

scala> mycomp("abc",20)
res129: Boolean = true

scala> arr1.sortWith(mycomp)    // 括号里需要函数,函数有两个参数,返回boolean型
res130: Array[Any] = Array(world, hello, are, abc, 20)

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

scala> mycomp(("abc",20))
res132: Boolean = true

scala> arr1.sortWith(mycomp)
<console>:15: error: type mismatch;
 found   : ((Any, Any)) => Boolean
 required: (Any, Any) => Boolean
       arr1.sortWith(mycomp)
                     ^
					 
scala> def mycomp(x:Any,y:Any):Boolean = (x,y) match{
     |     case (f:String,g:String) => f > g
     |     case (f:Integer,g:String) => f.toString > g
     |     case (f:String,g:Integer) => f > g.toString
     |     case (f:Integer,g:Integer) => f > g
     | }
mycomp: (x: Any, y: Any)Boolean

// Any类型无法比较大小
scala> arr1.partition(x => x.isInstanceOf[Int])
res139: (Array[Any], Array[Any]) = (Array(20),Array(hello, world, are, abc))

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

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

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

scala> val t2 = Array(20,"abc")
t2: Array[Any] = Array(20, abc)

scala> arr1.endsWith(t2)
res152: Boolean = true

stringPrefix返回 toString 结果的前缀

scala> arr1.slice(1,3)   // subSequence
res154: Array[Any] = Array(world, are)

scala> arr1.take(3)   // 拿前三个元素
res155: Array[Any] = Array(hello, world, are)

scala> arr1.takeWhile(_.isInstanceOf[String])
res158: Array[Any] = Array(hello, world, are)

scala> arr1.toIterator
res159: Iterator[Any] = non-empty iterator
scala> arr1.toList
res160: List[Any] = List(hello, world, are, 20, abc)

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

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   // 行转列
res161: Array[Array[Int]] = Array(Array(3, 7, 10), Array(4, 8, 11), Array(5, 9, 12))

union并集

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
res161: Array[Array[Int]] = Array(Array(3, 7, 10), Array(4, 8, 11), Array(5, 9, 12))

scala> val ar1 = Array(Array(3,4,5),Array(7,8,9))
ar1: Array[Array[Int]] = Array(Array(3, 4, 5), Array(7, 8, 9))

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

scala> val ar1 = Array((3,4),(7,8))    // 必须数组里元素为元祖,必须2*2
ar1: Array[(Int, Int)] = Array((3,4), (7,8))

scala> ar1.unzip
res163: (Array[Int], Array[Int]) = (Array(3, 7),Array(4, 8))

scala> arr
res164: Array[String] = Array(hello, world, are)

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

scala> arr1(3) = 60

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

scala> arr1.update(3,80)

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

scala> arr1.updated(3,100)
res170: Array[Any] = Array(hello, world, are, 100, abc)

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

scala> arr.view(1,3)
res172: scala.collection.mutable.IndexedSeqView[String,Array[String]] = SeqViewS(...)

scala> arr1.view(1,3).foreach(x => println(x))
world
are
scala> t1
res174: Array[String] = Array(world, are)

scala> t2
res175: Array[Any] = Array(20, abc)

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

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

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

scala> t3.zipAll(t1,0,3)  // t3少就补3,t1少就补0
res178: Array[(Int, Any)] = Array((1,world), (2,are), (3,3), (4,3), (5,3))

scala> t1.zipAll(t3,0,3)
res179: Array[(Any, Int)] = Array((world,1), (are,2), (0,3), (0,4), (0,5))

scala> t3.zipWithIndex  // 自动配索引
res180: Array[(Int, Int)] = Array((1,0), (2,1), (3,2), (4,3), (5,4))

scala> arr1.zipWithIndex
res182: Array[(Any, Int)] = Array((hello,0), (world,1), (are,2), (80,3), (abc,4))

scala> arr1.transform(_+"10")   // 对每个元素自动处理
res183: scala.collection.mutable.WrappedArray[Any] = WrappedArray(hello10, world10, are10, 8010, abc10)

scala> arr1.toVector
res184: Vector[Any] = Vector(hello10, world10, are10, 8010, abc10)
scala> import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ListBuffer

scala> var e = ListBuffer(1,2,3)
e: scala.collection.mutable.ListBuffer[Int] = ListBuffer(1, 2, 3)

scala> e+=10  // 修改自身
res187: scala.collection.mutable.ListBuffer[Int] = ListBuffer(1, 2, 3, 10)

scala> e:+10   // 自身不改,返回值修改
res188: scala.collection.mutable.ListBuffer[Int] = ListBuffer(1, 2, 3, 10, 10)

scala> e
res189: scala.collection.mutable.ListBuffer[Int] = ListBuffer(1, 2, 3, 10)

scala> e++=ListBuffer(7,8,9)   // 后加集合
res190: scala.collection.mutable.ListBuffer[Int] = ListBuffer(1, 2, 3, 10, 7, 8, 9)


scala> e++=:ListBuffer(6,5)     // 自身不改,返回值加上新集合
res193: scala.collection.mutable.ListBuffer[Int] = ListBuffer(1, 2, 3, 10, 7, 8, 9, 6, 5)

scala> e
res194: scala.collection.mutable.ListBuffer[Int] = ListBuffer(1, 2, 3, 10, 7, 8, 9)

scala> 100::k
res195: List[Int] = List(100, 1, 2, 3)

scala> k
res196: List[Int] = List(1, 2, 3)

scala> k::100
<console>:14: error: value :: is not a member of Int
       k::100
        ^
		
scala> k:+100
res198: List[Int] = List(1, 2, 3, 100)

scala> 100+:k
res199: List[Int] = List(100, 1, 2, 3)

scala> k
res200: List[Int] = List(1, 2, 3)

scala> k:::List(3,4,5)     // :::两个集合并一起
res201: List[Int] = List(1, 2, 3, 3, 4, 5)

scala> k++:List(3,4,5)   // 有:的都是自身不变的
res204: List[Int] = List(1, 2, 3, 3, 4, 5)

scala> k
res205: List[Int] = List(1, 2, 3)

scala> var f = Set(1,2,3)    // set不能重复,去重用toset再赚回来
f: scala.collection.immutable.Set[Int] = Set(1, 2, 3)

scala> f+=20

scala> f
res207: scala.collection.immutable.Set[Int] = Set(1, 2, 3, 20)

scala> f+=20

scala> f
res209: scala.collection.immutable.Set[Int] = Set(1, 2, 3, 20)

// 去重
scala> val arr = Array(1,2,3,4,5,4,3)
arr: Array[Int] = Array(1, 2, 3, 4, 5, 4, 3)

scala> arr.toSet.toArray
res210: Array[Int] = Array(5, 1, 2, 3, 4)   

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

scala> var e = Set(1,2,3,4)
e: scala.collection.mutable.Set[Int] = Set(1, 2, 3, 4)

scala> var k = Set(4,5,6)
k: scala.collection.mutable.Set[Int] = Set(5, 6, 4)

scala> e & k
res216: scala.collection.mutable.Set[Int] = Set(4)

scala> e | k
res217: scala.collection.mutable.Set[Int] = Set(1, 5, 2, 6, 3, 4)

scala> k &~ e
res218: scala.collection.mutable.Set[Int] = Set(5, 6)

scala> e &~ k
res220: scala.collection.mutable.Set[Int] = Set(1, 2, 3)
scala> arr.grouped(3).toList.foreach(x => println(x.sorted.mkString(",")))
Dwan,Jason,Vince
Lynn,Stephon

scala> arr.grouped(3).toList.foreach(x => println(x.sorted.mkString("List{",",","}")))
List{Dwan,Jason,Vince}
List{Lynn,Stephon}

scala> arr.grouped(3).toList.foreach(x => println(x.sorted)
     | )
List(Dwan, Jason, Vince)
List(Lynn, Stephon)

scala> arr.splitAt(3)
res231: (List[String], List[String]) = (List(Jason, Vince, Dwan),List(Lynn, Stephon))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值