微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Scala入门二

数组

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 Person {
  private var name=""
  private var age=0
  
  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")
  }
}

测试

package com.yasuofenglei.test

object Demo07 {
	val p1=new Person                         //> p1  : com.yasuofenglei.test.Person = com.yasuofenglei.test.Person@50134894
	p1.setName("tom")
	p1.setAge(23)
	
	p1.getName                                //> res0: String = tom
	p1.getAge                                 //> res1: Int = 23
	
	p1.say                                    //> hello
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐