Scala集合库、模式匹配和样例类
package com.yz8 import org.junit.Test class test { @Test def test: Unit = { val ints = List(1,5,7,6,8) println(ints.head)//1 println(ints.tail)//List(5, 7, 6, 8) //判断集合是否为空 println(ints.isEmpty) println(ints==Nil) } @Test def test2(): Unit ={ val ints = List(1,5,7,6,8) def sum(list:List[Int]): Int ={ if(list==Nil){ return 0 } list.head+sum(list.tail) } val i = sum(ints) println(i)//27 //一般不用return返回值 一般当作break来用 } @Test def test3():Unit={ //会产生一个新的集合,不是对原有集合的更改 //集合的首尾添加 val a=List(1,2,3) val b=List(5,6,7) //尾添加 val c=a.++(b)//1 println(c) //首添加 (除了点以外三个符号) val d=a.++:(b) println(d) val e=a.:::(b) println(e) //尾部添加元组 val f=a.:+(7,8,9)//2 println(f)//List(1, 2, 3, (7,8,9)) //首部加元组 (除了点以外两个符号) val g = a.+:(7,8,9) println(g) val h = a.::(7,8,9) println(h) } @Test def test4():Unit={ val a=List(1,2,3,4,5,6,7,8,9) val b = a.drop(3) println(b)//List(4, 5, 6, 7, 8, 9) val c = a.dropRight(3) println(c)//List(1, 2, 3, 4, 5, 6) val a2=List(8,2,2,1,5,7,9) // val d = a2.dropWhile(_%2==0) val d = a2.dropWhile((x)=>x%2==0)//逐个匹配去除符合条件的元素,直到不符合条件,之后的元素不再判断 println(d)//List(1, 5, 7, 9) //查询 println( a2(0)) //修改 //a2(0)=999// 修改失败 不导包不能修改,因为List默认是不可变包中的List println(a2(0)) val ints = scala.collection.mutable.ListBuffer[Int](1,5,6) println(ints(0)) ints(0)=999 println(ints(0)) } //A=B B=C 推出A=C 等效推算(定义变量/定义集合这些存数据的地方,默认常用不可变) 很多东西默认不可变,更符合机器逻辑 @Test def test5(): Unit ={ val a="ccc"::("bbb"::("aaa"::Nil)) println(a)//List(ccc, bbb, aaa) val b=List(1,2,3) val c=List(3,4,5) val d=b++c//List(1, 2, 3, 3, 4, 5) println(d) println(b.sum)//6 val list = List(1, 2, 3, 4, 5, 6, 7) println(list.take(5))//List(1, 2, 3, 4, 5) println(list.takeWhile(_<=3))//List(1, 2, 3) println(list.takeWhile(_>3))//List() println(list.mkString)//1234567 println(list.count(_%2==0))//3 } }
package com.yz8 import org.junit.Test import scala.beans.BeanProperty import scala.collection.mutable class test2 { @Test def test1(): Unit ={ val set=Set(1,2,6) val set2=set+(1,2,8) set2.foreach(println(_)) } @Test def test2(): Unit ={ //set不保留添加顺序 val set=Set(1,2,6,'a','b') set.foreach(println(_)) //1 //6 //97 //2 //98 //linkHashSet保留添加顺序 val linkset=scala.collection.mutable.LinkedHashSet(1,3,6,'a','b') linkset.foreach(println(_)) //1 //3 //6 //97 //98 println("__________") //SortedSet 默认升序 val sortedset=scala.collection.mutable.SortedSet(1,4,6,-100,-1) sortedset.foreach(println(_)) } @Test def test3(): Unit ={ //按名字升序,按年龄升序[向集合中传递一个比较器] var set=mutable.SortedSet[Person]()(new Ordering[Person] { override def compare(x: Person, y: Person): Int = { //按名字比较 val ret=x.getName.compareTo(y.getName) if(ret==0){ val ret=x.getAge.compareTo(y.getAge) } ret } }) set.add(new Person("a",20)) set.add(new Person("w",30)) set.add(new Person("e",50)) set.add(new Person("f",10)) set.foreach(println(_)) } @Test def test4(): Unit ={ //命题:按年龄升序,如果相同,名字降序 val set = mutable.SortedSet[Person2]() set.add(new Person2("a",20)) set.add(new Person2("w",30)) set.add(new Person2("e",50)) set.add(new Person2("f",10)) set.foreach(println(_)) //两种方式实现SortedSet的比较规则: // 1在SortedSet中传递Ordering的比较器 //2被比较对象类中extends Ordered特质 //2选1 本质上两种方式都是重写了compare()方法 } @Test def test5(): Unit ={ //foreach val data=1 to 10 //data.foreach(println(_)) //高阶函数 data.foreach(x=>println(x)) println("-------------") val list = List("aa","bb","cc","dd") //val strings = list.map(_+1+4) val strings = list.map(x=>x+1+4) //将元素作用在一个函数上 //y=x+1 strings.foreach(println(_)) //flatMap println("----------------") val list2 = List("aa bb cc","aa ff","cc","ww cc") //分割单词 list2.flatMap(_.split(" ")).foreach(println(_)) } @Test def test6(): Unit ={ //匹配 var name="" val ch:Char='7' name=ch match { case 'b'=>"小明" case 'a'=>"小红" case 'w'=>"小黑" case 'f'=>"小白" case _ if Character.isDigit(ch)=>"王思冲"//一般把case _放在末尾,放在第一行不管什么情况都会只执行该语句 //如果没有_ 匹配不上会报MatchError case _ if Character.isAlphabetic(ch)=>"薛之谦" } println(name) } @Test def test7(): Unit ={ //相当于 .foreach() "Hello, world" foreach(c=>println( c match { case ' '=>"空格" case y=>"中国"+y //y不是去匹配,而是作为变量接收值 } //case后如果写值,就表示匹配这个值,如果写变量名,就表示接收这个值 )) //中国H //中国e //中国l //中国l //中国o //中国, //空格 //中国w //中国o //中国r //中国l //中国d } @Test def test8(): Unit ={ //println(Int.MaxValue)//2147483647 //代替isInstanceOf和asInstanceOf def myConvert(x:Any):Int={ val retust= x match { case i:Int=>i case s:String=>Integer.parseInt(s) case m:BigInt=>Int.MaxValue case c:Char=>c.toInt case _=>0 } retust } val res1 = myConvert("123") println(res1==123)//true val res2 = myConvert(true) println(res2) } @Test def test9(): Unit ={ val tup=(5,6)//注元组中无法匹配这两种情况既case(x,y)和case_ tup match { case (1,2)=>println(1,2) case (0,_)=>println(0+".....")//元组中不能用_* case (x,y)=>println(x+"...."+y) case _=>println("其它情况") } } @Test def test10(): Unit ={ val array = Array(1) array match { case Array(0)=>println(0)//只有一个元素且为0 case Array(x,y)=>println(x+" "+y)//两个元素 case Array(0,_*)=>println(0+"...")//任意以0开头 case _=>println("else") } } @Test def test11(): Unit ={ //样例类(类前加case 关键字)--可以用match case结构中 case class Abc(name:String) case class Efg(name:String,age:Int) case class Xyz(name:String,address:String) //样例类会自动为属性添加get set 也会字段提供伴生对象 val abc = Abc("小白")//创建了一个abc对象 println(abc.name) var x=Efg("哈哈",100) x match { case Abc(name)=>println(s"$name") case Efg(name,age)=>println(s"$name----$age") case Xyz(name,address)=>println(s"$name-----$address") case _=>println("默认选项") } } @Test def test12(): Unit ={ //样例类 模拟枚举(列举) sealed abstract class TrafficLightColor//交通灯 case object Red extends TrafficLightColor case object Yellow extends TrafficLightColor case object Green extends TrafficLightColor def show(color:TrafficLightColor):Unit={ color match { case Red => println("红灯") case Yellow => println("黄灯") case Green => println("绿灯") } } show(Yellow) } @Test def test13(): Unit ={ //了解option--兼容有值Some()或没值None 可以支持泛型 val map = Map("a"->10,"b"->20,"c"->30) def show(x:Option[Int]): Unit ={ x match { case Some(s)=>println(s) case None=>println("没值") } } show(map.get("f"))//没值 show(map.get("a"))//10 println(map.get("a"))//Some(10) println(map.get("e"))//None } @Test def test14(): Unit ={ val a:Option[Int]=Some(5) val b:Option[Int]=None //能取到值就取出原值,取不出就取出默认值 println(a.getOrElse(0))//5 println(b.getOrElse(100))//100 println(a.isEmpty)//判断是否为空 println(b.isEmpty) } } class Person{ @BeanProperty var name:String=_ @BeanProperty var age:Int=_ override def toString = s"Person($name, $age)" def this(n:String,a:Int){ this() this.name=n this.age=a } } class Person2 extends Ordered[Person2]{ @BeanProperty var name:String=_ @BeanProperty var age:Int=_ override def toString = s"Person($name, $age)" def this(n:String,a:Int){ this() this.name=n this.age=a } override def compare(that: Person2): Int = { //升序--前者比后者 //降序--后者比前者 //命题:按年龄升序,如果相同,名字降序 val ret = this.age.compareTo(that.age) if(ret==0){ val ret = that.name.compareTo(this.name) } ret } }