数组
package com.yasuofenglei.test
import scala.collection.mutable._
object Demo02 {
val v1=100 //> v1 : Int = 100
//懒加载,声明时不是马上赋值,被调用时才会被赋值,只能修饰常量val,不能修饰变量var
lazy val v2=100 //> v2: => Int
print(v1) //> 100
print(v2) //> 100
/*
scala的集合collection类型包含:
Array,List,Set,Map,Tuple
*/
//声明一个定长数组并赋值。定长immutable:一经声明,长度不能修改
val a1=Array(1,2,3,4,5,6) //> a1 : Array[Int] = Array(1, 2, 3, 4, 5, 6)
//声明一个定长为3的数组,但没有赋值
val a2=new Array[Int](3) //> a2 : Array[Int] = Array(0, 0, 0)
//声明一个变长数组。变长mutable:声明之后,可以追加(长度可变)
val a3=ArrayBuffer(1,2,3,4) //> a3 : scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1, 2, 3, 4)
//通过下标取值或赋值
a1(0) //> res0: Int = 1
a1(0)=10
a1 //> res1: Array[Int] = Array(10, 2, 3, 4, 5, 6)
a3.append(5)
a3 //> res2: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1, 2, 3, 4, 5)
//|
val a5=Array(1,2,3,4,5,6) //> a5 : Array[Int] = Array(1, 2, 3, 4, 5, 6)
//取前n个元素的数组
val r1=a5.take(3) //> r1 : Array[Int] = Array(1, 2, 3)
//取后n个元素的数组
val r2=a5.takeRight(2) //> r2 : Array[Int] = Array(5, 6)
//取出头一个元素
val r3=a5.head //> r3 : Int = 1
//删除n个元素并返回剩余部分
val r5=a5.drop(2) //> r5 : Array[Int] = Array(3, 4, 5, 6)
val r6=a5.dropRight(2) //> r6 : Array[Int] = Array(1, 2, 3, 4)
//取最后一个元素
val r7=a5.last //> r7 : Int = 6
//最大
val r9=a5.max //> r9 : Int = 6
//最小
val r10=a5.min //> r10 : Int = 1
//求和
val r11=a5.sum //> r11 : Int = 21
//计算a5均值
val r12=a5.sum*1.0/a5.length //> r12 : Double = 3.5
//去重
val a6=Array(1,1,2,2,3,4) //> a6 : Array[Int] = Array(1, 1, 2, 2, 3, 4)
val r13=a6.distinct //> r13 : Array[Int] = Array(1, 2, 3, 4)
val a7=Array(1,2,3) //> a7 : Array[Int] = Array(1, 2, 3)
val a8=Array(5,6,3) //> a8 : Array[Int] = Array(5, 6, 3)
//取交集
val r14=a7.intersect(a8) //> r14 : Array[Int] = Array(3)
//取并集
val r15=a7.union(a8) //> r15 : Array[Int] = Array(1, 2, 3, 5, 6, 3)
//差集
val r16=a7.diff(a8) //> r16 : Array[Int] = Array(1, 2)
val r17=a8.diff(a7) //> r17 : Array[Int] = Array(5, 6)
//数组转字符串
var r18=a7.mkString //> r18 : String = 123
var r182=a7.mkString(",") //> r182 : String = 1,2,3
//反转
val r19=a7.reverse //> r19 : Array[Int] = Array(3, 2, 1)
//过滤
val r20=a7.filter{x => x>1} //> r20 : Array[Int] = Array(2, 3)
//计算出a9中成年人的年龄之和
val a9=Array(14,22,16,25,30,40,18) //> a9 : Array[Int] = Array(14, 22, 16, 25, 30, 40, 18)
val r21=a9.filter{x => x>=18}.sum //> r21 : Int = 135
//统计出未 成年中的最大年龄
val r22=a9.filter{x => x<18}.max //> r22 : Int = 16
//计数,大于20的
val r23=a9.count { x => x>20 } //> r23 : Int = 4
//返回a10和a11中不重复的偶数个数
val a10=Array(1,2,3,4) //> a10 : Array[Int] = Array(1, 2, 3, 4)
val a11=Array(3,4,5,6) //> a11 : Array[Int] = Array(3, 4, 5, 6)
val r24=a10.union(a11).distinct.count(_%2==0) //> r24 : Int = 3
//判断是否存在符合条件的元素
val r25=a10.exists{x => x>5} //> r25 : Boolean = false
//判断a12中是否存在非法的手机号(合法的是11位)
val a12=Array("131","1311","13111","11111111111")
//> a12 : Array[String] = Array(131, 1311, 13111, 11111111111)
val r26=a12.exists( _.length !=11) //> r26 : Boolean = true
//排序
val a13=Array(2,1,4,5,6) //> a13 : Array[Int] = Array(2, 1, 4, 5, 6)
val r27=a13.sortBy{num => num } //> r27 : Array[Int] = Array(1, 2, 4, 5, 6)
val r28=a13.sortBy{num => num }.reverse //> r28 : Array[Int] = Array(6, 5, 4, 2, 1)
//要求操作a14按年龄做升序排序
val a14=Array("tom 23","rose 18","jim 35","jary 20","k 3")
//> a14 : Array[String] = Array(tom 23, rose 18, jim 35, jary 20, k 3)
val r29=a14.sortBy{s => s.split(" ")(1).toInt} //> r29 : Array[String] = Array(k 3, rose 18, jary 20, tom 23, jim 35)
val r30=a14.sortBy{s => s.split(" ")(1)} //> r30 : Array[String] = Array(rose 18, jary 20, tom 23, k 3, jim 35)
//操作a14,取出年龄最大的两个人数据
val r31=a14.sortBy{s => s.split(" ")(1).toInt}.takeRight(2)
//> r31 : Array[String] = Array(tom 23, jim 35)
//映射成一个新的集合
val a15=Array(1,2,3,4) //> a15 : Array[Int] = Array(1, 2, 3, 4)
val r32=a15.map{x => x*2} //> r32 : Array[Int] = Array(2, 4, 6, 8)
val r33=a15.map{num => num.toString()} //> r33 : Array[String] = Array(1, 2, 3, 4)
//操作a16,返回的数组中,只包含姓名信息
val a16=Array("tom M 23","rose F 20","jim M 35")//> a16 : Array[String] = Array(tom M 23, rose F 20, jim M 35)
val r34=a16.map(p => p.split(" ")(0)) //> r34 : Array[String] = Array(tom, rose, jim)
//统计出年龄最大的前2个人的年龄之和
val r35=a16.map{line => line.split(" ")(2).toInt}.sortBy(line => line.toInt).takeRight(2).sum
//> r35 : Int = 58
//reduce规约方法,底层是一种迭代
/*
a=1 b=2
a=3 b=3
a=6 b=4
*/
val a17=Array(1,2,3,4,5) //> a17 : Array[Int] = Array(1, 2, 3, 4, 5)
val r36=a17.reduce{(a,b)=>a+b} //> r36 : Int = 15
//计算6的阶乘
val a18=Array(1,2,3,4,5,6) //> a18 : Array[Int] = Array(1, 2, 3, 4, 5, 6)
val a37=a18.reduce{(a,b)=>a*b} //> a37 : Int = 720
println("") //>
}
List
package com.yasuofenglei.test
import scala.collection.mutable.ListBuffer
/*
Array 和List通用而且重要的方法
take
takeRight
drop
dropRight
head
last
max
min
sum
mkString
intersect
union
diff
filter
sortBy
count
exists
map
reduce
distinct
foreach
*/
object Demo03 {
//声明一个定长list
val l1=List(1,2,3,4) //> l1 : List[Int] = List(1, 2, 3, 4)
//声明一个定长List,并指定长度
val l2=List[Int](3) //> l2 : List[Int] = List(3)
//--声明一个
val l3=ListBuffer(1,2,3,4) //> l3 : scala.collection.mutable.ListBuffer[Int] = ListBuffer(1, 2, 3, 4)
l1.foreach{x=>println(x)} //> 1
//| 2
//| 3
//| 4
//基于某个List追加元素并返回新的List
val l4 = l1.::(5) //> l4 : List[Int] = List(5, 1, 2, 3, 4)
val l5=List(1,1,2,2,3) //> l5 : List[Int] = List(1, 1, 2, 2, 3)
l5.distinct //> res0: List[Int] = List(1, 2, 3)
l5.toArray.distinct.toList //> res1: List[Int] = List(1, 2, 3)
}
Set
package com.yasuofenglei.test
object Demo04 {
//声明定长set
val s1=Set(1,1,2,2,3) //> s1 : scala.collection.immutable.Set[Int] = Set(1, 2, 3)
val s2=scala.collection.mutable.Set(1,2,3,4) //> s2 : scala.collection.mutable.Set[Int] = Set(1, 2, 3, 4)
val s3=Set(1,2,3) //> s3 : scala.collection.immutable.Set[Int] = Set(1, 2, 3)
val s4=Set(3,4,5) //> s4 : scala.collection.immutable.Set[Int] = Set(3, 4, 5)
//交集
s3.intersect(s4) //> res0: scala.collection.immutable.Set[Int] = Set(3)
s3&s4 //> res1: scala.collection.immutable.Set[Int] = Set(3)
//并集
s3.union(s4) //> res2: scala.collection.immutable.Set[Int] = Set(5, 1, 2, 3, 4)
s3++s4 //> res3: scala.collection.immutable.Set[Int] = Set(5, 1, 2, 3, 4)
//差集
s3.diff(s4) //> res4: scala.collection.immutable.Set[Int] = Set(1, 2)
s3&~s4 //> res5: scala.collection.immutable.Set[Int] = Set(1, 2)
//
}
Map
package com.yasuofenglei.test
object Demo05 {
//声明一个定长map
val m1=Map("tom"->23,"rose"->30) //> m1 : scala.collection.immutable.Map[String,Int] = Map(tom -> 23, rose -> 30)
//|
//声明一个变长map
val m2=scala.collection.mutable.Map("tom"->23,"rose"->30)
//> m2 : scala.collection.mutable.Map[String,Int] = Map(rose -> 30, tom -> 23)
//|
//通过key获取对应的value
m1.apply("tom") //> res0: Int = 23
m1 apply "tom" //> res1: Int = 23
m1("tom") //> res2: Int = 23
/*get取值返回的是一个Option类型的
Option有两个字类:Some,None
如果指定的key有value,就将value封装到Som里
如果指定的key没有,就返回None
*/
m1.get("tom") //> res3: Option[Int] = Some(23)
m1.get("k") //> res4: Option[Int] = None
//通过getOrElse取值,参数为默认值
m1.get("tom").getOrElse(0) //> res5: Int = 23
//针对变长map追加
m2+=("jim"->33,"lucy"->18) //> res6: com.yasuofenglei.test.Demo05.m2.type = Map(jim -> 33, rose -> 30, tom
//| -> 23, lucy -> 18)
//返回m1的key,value的迭代器
m1.keys //> res7: Iterable[String] = Set(tom, rose)
m1.values //> res8: Iterable[Int] = MapLike(23, 30)
//过滤,case匹配的使用方法
val r1=m1.filter{case(k,v) => v>25} //> r1 : scala.collection.immutable.Map[String,Int] = Map(rose -> 30)
//操作m1,人名不变,年龄加10岁
val r2=m1.map{case(k,v)=>(k,v+10)} //> r2 : scala.collection.immutable.Map[String,Int] = Map(tom -> 33, rose -> 40
//| )
//操作map时,如果只针对Map的value做映射
val r3=m1.mapValues{x => x+10} //> r3 : scala.collection.immutable.Map[String,Int] = Map(tom -> 33, rose -> 40
//| )
//遍历
m1.foreach{x=>println(x)} //> (tom,23)
//| (rose,30)
val r4=m1.toArray //> r4 : Array[(String, Int)] = Array((tom,23), (rose,30))
val r5=m1.toList //> r5 : List[(String, Int)] = List((tom,23), (rose,30))
}
元组
package com.yasuofenglei.test
//元组操作
object Demo06 {
//声明一个包含4个元素的元组
val t1=(1,2,3,4) //> t1 : (Int, Int, Int, Int) = (1,2,3,4)
val t2=(1,"hello",Array(1,2,3),List(3,4)) //> t2 : (Int, String, Array[Int], List[Int]) = (1,hello,Array(1, 2, 3),List(3,
//| 4))
//元组取值
t2._2 //> res0: String = hello
val t3=((1,2),Array(3,4,5),(6,7,8)) //> t3 : ((Int, Int), Array[Int], (Int, Int, Int)) = ((1,2),Array(3, 4, 5),(6,7
//| ,8))
t3._3._2 //> res1: Int = 7
t3._2(2) //> res2: Int = 5
//过滤出年龄>25的数据
val m1=Map("tom"->23,"rose"->30) //> m1 : scala.collection.immutable.Map[String,Int] = Map(tom -> 23, rose -> 30
//| )
val r1=m1.filter{case(k,v)=>v>25} //> r1 : scala.collection.immutable.Map[String,Int] = Map(rose -> 30)
val r2=m1.filter{x=> x._2>25} //> r2 : scala.collection.immutable.Map[String,Int] = Map(rose -> 30)
val l1=List(("b",3),("a",4),("c",1),("d",2))
//> l1 : List[(String, Int)] = List((b,3), (a,4), (c,1), (d,2))
//对l1,根据字母升序排序
l1.sortBy{x=>x._1} //> res3: List[(String, Int)] = List((a,4), (b,3), (c,1), (d,2))
//l1数字做降序
l1.sortBy{x=> -x._2} //> res4: List[(String, Int)] = List((a,4), (b,3), (d,2), (c,1))
val r5=l1.sortBy{case(col1,col2)=> -col2} //> r5 : List[(String, Int)] = List((a,4), (b,3), (d,2), (c,1))
val l2=List(("hello",1),("hello",1),("world",1),("hello",1))
//> l2 : List[(String, Int)] = List((hello,1), (hello,1), (world,1), (hello,1))
//|
//操作l2,返回新的List("hello","world),去重
val r6=l2.distinct.map{x=>x._1} //> r6 : List[String] = List(hello, world)
val r7=l2.distinct.map{case(word,num)=>word}
//> r7 : List[String] = List(hello, world)
val l3=List(("tom","M",15000),("rose","F",16000),("jim","M",10000),("jim","M",12000))
//> l3 : List[(String, String, Int)] = List((tom,M,15000), (rose,F,16000), (jim
//| ,M,10000), (jim,M,12000))
//男性薪资最高的前两名的工资和
l3.filter{x=>x._2=="M"}.sortBy{x=> -x._3}.take(2).map(_._3).sum
//> res5: Int = 27000
val l4=List("hello world","hello hadoop","hello world")
//> l4 : List[String] = List(hello world, hello hadoop, hello world)
val r9=l4.map{line => line.split(" ")} //> r9 : List[Array[String]] = List(Array(hello, world), Array(hello, hadoop),
//| Array(hello, world))
//扁平化map,改变元素的形式,也改变元素个数,一般的使用场景是读取文件后,将每一行的数据拿到
val r10=l4.flatMap{line => line.split(" ")}
//> r10 : List[String] = List(hello, world, hello, hadoop, hello, world)
val l5=List("hello","hello","world","hello","world")
//> l5 : List[String] = List(hello, hello, world, hello, world)
//按照指定的匿名函数规则做分组,返回的是一个Map(key,value),key是分组字段value是相同数据组成的List
val r11=l5.groupBy{word => word} //> r11 : scala.collection.immutable.Map[String,List[String]] = Map(world -> L
//| ist(world, world), hello -> List(hello, hello, hello))
//操作l6按地区分组
val l6=List(("bj",1),("sh",2),("bj",3),("sh",4))//> l6 : List[(String, Int)] = List((bj,1), (sh,2), (bj,3), (sh,4))
val r12=l6.groupBy{x=> x._1} //> r12 : scala.collection.immutable.Map[String,List[(String, Int)]] = Map(bj
//| -> List((bj,1), (bj,3)), sh -> List((sh,2), (sh,4)))
//统计每个单词的频次
val l7=List("hello world hadoop","hello world","hello hadoop")
//> l7 : List[String] = List(hello world hadoop, hello world, hello hadoop)
val r13=l7.flatMap(line => line.split(" ")).groupBy{x => x}.map{x =>(x._1,(x._2).count(p=> true))}
//> r13 : scala.collection.immutable.Map[String,Int] = Map(hadoop -> 2, world
//| -> 2, hello -> 3)
val r14=l7.flatMap(line => line.split(" ")).groupBy{x => x}.map{x =>(x._1,(x._2).map{x=> 1}.sum)}
//> r14 : scala.collection.immutable.Map[String,Int] = Map(hadoop -> 2, world
//| -> 2, hello -> 3)
val r15=l7.flatMap(line => line.split(" ")).groupBy{x => x}.map{x =>(x._1,(x._2).size)}
//> r15 : scala.collection.immutable.Map[String,Int] = Map(hadoop -> 2, world
//| -> 2, hello -> 3)
val r16=l7.flatMap{line=>line.split(" ")}.groupBy{word => word}.mapValues{list=>list.size}.toList
//> r16 : List[(String, Int)] = List((hadoop,2), (world,2), (hello,3))
}
类 class
定义一个Person类
package com.yasuofenglei.test
/*
* scala同java一样,通过class关键字定义类
* 可以定义成员变量和成员方法
* 默认的访问权限是public(没有public关键字)。此外可以通过private 或者 protected 来修饰
* class的方法支持重写和重载,定义同java
* clall有一个主构造器,可以有多个辅助构造器
* */
class Person(v1:String,v2:Int) {
private var name=v1
private var age=v2
def setName(name:String)={
this.name=name
}
def getName()={
this.name
}
def setAge(age:Int)={
this.age=age
}
def getAge()={
this.age
}
def say()={
println("hello "+this.name)
}
//定义一个辅助构造器
//要求必须调用本类的主构造器
def this(v1:String){
this(v1,0)
}
def this(v2:Int){
this("def",v2)
}
def this(){
this("def",0)
}
}
测试
package com.yasuofenglei.test
object Demo07 {
val p1=new Person("jack",100) //> p1 : com.yasuofenglei.test.Person = com.yasuofenglei.test.Person@50134894
p1.getName //> res0: String = jack
p1.getAge //> res1: Int = 100
p1.say //> hello jack
val p2=new Person("rose") //> p2 : com.yasuofenglei.test.Person = com.yasuofenglei.test.Person@3f3afe78
p1.getName //> res2: String = jack
p1.getAge //> res3: Int = 100
p2.say //> hello rose
}
继承
package com.yasuofenglei.test
/*
* 通过extends来继承
* 单继承
* 重写方法需要加override
* 重写抽象方法不需要加override
*/
class Student extends Person{
override def say(){
println("stu say")
}
}
抽象类
package com.yasuofenglei.test
/*
* 通过abstract定义一个抽象类
* 可以定义抽象方法和普通方法
* 抽象方法没有方法体
*/
abstract class Teacher {
//抽象方法
def makeNote(line:String):String
def teach():Unit
//普通方法
def speak()={}
}
继承抽象类
package com.yasuofenglei.test
class LiuTeacher extends Teacher {
def makeNote(line: String): String = {
???
}
def teach(): Unit = {
???
}
override def speak()={
}
}
trait(特质,相当于接口)
trait中可以有普通方法,在单继承前提下可以实现多继承的效果
package com.yasuofenglei.test
/*
* scala的trait类比于java的Interface
* trait(特质),可以定义抽象方法
*/
trait Dance {
def balei():Int
def tiTa():String
def floor()={}
}
实现接口
scala是单继承,多混入的
scala要求必须有而且仅有一个extends
可以extends trait类
class LiuTeacher extends Teacher with Dance with Drive{
}
package com.yasuofenglei.test
class LiuTeacher extends Teacher with Dance {
def makeNote(line: String): String = {
???
}
def teach(): Unit = {
???
}
override def speak()={
}
def balei(): Int = {
???
}
def tiTa(): String = {
???
}
}
object 单例类
package com.yasuofenglei.test
/*
* 知识点
* 1.scala object 单例对象类。
* 定义的变量和方法都是静态
* */
object Util {
def sleep()={
println("Zzz");
}
}
如果要给一个类定义一个静态方法,则在该文件中中定义一个object,object名与类名一致。在object中添加方法。
class稳为object的伴生类
object称为class的伴生对象
package com.yasuofenglei.test
class Person
object Person{
def speak()={
//相当于为person类定义一个静态方法
}
}
case class 样列类
package com.yasuofenglei.test
/*
*
通过case关键字来定义一个样列类
case class必须声明一个主构造器
当声明一个主构造器后,case class会默认声明一个空的辅助构造器
case class 不需要new就可以创建类的实例对象
默认实现了toString方法
case class默认混入了序列化特殊(with Serializable)
*/
case class Item(val name:String,val age:Int) {
}
//测试
object Item{
val item1=Item("tom",23)
val item2=Item
}
练习
package com.yasuofenglei.test
import scala.collection.mutable._
object Demo08 {
//拉链操作,将对应 项的数据放在一起
val s1="hello" //> s1 : String = hello
val s2="world" //> s2 : String = world
s1 zip s2 //> res0: scala.collection.immutable.IndexedSeq[(Char, Char)] = Vector((h,w), (e
//| ,o), (l,r), (l,l), (o,d))
//进行拉链操作时,元素个数如果不一致,不产生该对应项
val a1=Array(1,2,3,4) //> a1 : Array[Int] = Array(1, 2, 3, 4)
val a2=Array("a","b","c") //> a2 : Array[String] = Array(a, b, c)
a1 zip a2 //> res1: Array[(Int, String)] = Array((1,a), (2,b), (3,c))
//定义一个函数values(fun:(Int)=>Int,low:Int,high:Int),该函数输出该范围内的计算结果集合
def f1(f:(Int)=>Int,start:Int,end:Int)={
val result=ListBuffer[(Int,Int)]()
for(i<- start to end){
result.append((i,f(i)))
}
result
} //> f1: (f: Int => Int, start: Int, end: Int)scala.collection.mutable.ListBuffer
//| [(Int, Int)]
f1(x=>x*10,1,10) //> res2: scala.collection.mutable.ListBuffer[(Int, Int)] = ListBuffer((1,10), (
//| 2,20), (3,30), (4,40), (5,50), (6,60), (7,70), (8,80), (9,90), (10,100))
//求数组内最大值
val a3=Array(2,1,5,4,3) //> a3 : Array[Int] = Array(2, 1, 5, 4, 3)
a3.reduce{(a,b)=>if(a>b)a else b} //> res3: Int = 5
//10阶乘
1 to 10 reduce{_*_} //> res4: Int = 3628800
//
def f2(f:(Int)=>Int,inputs:Seq[Int])={
//val s=inputs.reduce{(a,b)=>if(f(a)>f(b)) a else b}
//f(s)
f(inputs.reduce{(a,b)=>if(f(a)>f(b))a else b})
} //> f2: (f: Int => Int, inputs: scala.collection.mutable.Seq[Int])Int
f2(x=>10*x-x*x,1 to 10 toArray) //> res5: Int = 25
//
val a4=Array(1,2,0,0,-3,-2,4,-6) //> a4 : Array[Int] = Array(1, 2, 0, 0, -3, -2, 4, -6)
def f4(arr:Array[Int])={
val arr1=for(i <- arr;if i>0)yield{i}
val arr2=for(i <- arr;if i==0)yield{i}
val arr3=for(i <- arr;if i<0)yield{i}
arr1 union arr2 union arr3
} //> f4: (arr: Array[Int])Array[Int]
f4(a4) //> res6: Array[Int] = Array(1, 2, 4, 0, 0, -3, -2, -6)
//
def f5(a:Int,b:Int):Option[Int]={
if(b!=0){
Some(a/b)
}else{
None
}
} //> f5: (a: Int, b: Int)Option[Int]
f5(4,2).getOrElse(0) //> res7: Int = 2
f5(4,0).getOrElse(0) //> res8: Int = 0
}