大数据系列修炼-Scala课程02

Scala数组操作实战详解

接着昨天的课程,下面我们继续学习关于Scala数组操作详解。
Scala数组的定义

//数组定义
//定长数组格式
/**
* val arrayName = new Array[datatype](length)
* val arrayName = Array(constant1,constant2,....)
*/
 //不定长数组定义格式
 /*
 * var arrayBufferName =ArrayBuffer[datatype]()
 */

数组的基本操作:包括截取(trimEnd),插入(insert),移除(remove),转换(toArray)等函数,居然发现eclipse开发工具中有一个很好的调试工具能够查看更多的变量值Scala Worksheet 非常好用!希望大家用用!

val b =ArrayBuffer[Int]()                      //> b  : scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer()
   b += 5                                         //> res0: com.dt.zhangsh.scala.ArrrayOp.b.type = ArrayBuffer(5)
   b                                              //> res1: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(5)
   b += (1,2,78,2)                                //> res2: com.dt.zhangsh.scala.ArrrayOp.b.type = ArrayBuffer(5, 1, 2, 78, 2)
   b ++= Array(45,2,1)                      //> res3: com.dt.zhangsh.scala.ArrrayOp.b.type = ArrayBuffer(5, 1, 2, 78, 2, 45,
                                                  //|  2, 1)
   b.trimEnd(5)
   b                                              //> res4: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(5, 1, 2)
   b.insert(2, 6)
   b                                              //> res5: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(5, 1, 6, 2)
   b.insert(2, 7, 8, 9)
   b                                              //> res6: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(5, 1, 7, 8, 9,
                                                  //|  6, 2)
   b.remove(2)                                    //> res7: Int = 7
   b                                              //> res8: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(5, 1, 8, 9, 6,
                                                  //|  2)
   b.remove(2, 3)
   b                                              //> res9: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(5, 1, 2)
   b.toArray                                      //> res10: Array[Int] = Array(5, 1, 2)

数组的进阶操作:进阶包括:求倍数(map)、求和(sum)、最大值(max)、排序(sorted)、快速排序(quickSort)、拼接(mkString)等函数

   //数组进阶
    val c = Array(2, 3, 5, 7, 11)                 //> c  : Array[Int] = Array(2, 3, 5, 7, 11)
    //数组乘以5 必须包含yield 用于结果输出
    val result = for (elem <- c) yield 5 * elem   //> result  : Array[Int] = Array(10, 15, 25, 35, 55)
    result                                        //> res11: Array[Int] = Array(10, 15, 25, 35, 55)
    //
    for (elem <- c if elem % 2 == 0) yield 2 * elem
                                                  //> res12: Array[Int] = Array(4)
     //_为占位符  如果能被2余数为0的数据放到map中并且乘以2
    c.filter(_ % 2 == 0).map(2 * _)               //> res13: Array[Int] = Array(4)
    c                                             //> res14: Array[Int] = Array(2, 3, 5, 7, 11)
    //求和
    Array(1, 7, 2, 9).sum                         //> res15: Int = 19
    //字符串最长
    ArrayBuffer("Mary", "had", "a", "little", "lamb").max
                                                  //> res16: String = little
    
    val d = ArrayBuffer(1, 7, 2, 9)               //> d  : scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1, 7, 2, 9)
    //排序
    val bSorted = d.sorted                        //> bSorted  : scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1, 2, 7,
                                                  //| 9)
    
    val e = Array(1, 7, 2, 9)                     //> e  : Array[Int] = Array(1, 7, 2, 9)
    //快速排序
    scala.util.Sorting.quickSort(e)
    e                                             //> res17: Array[Int] = Array(1, 2, 7, 9)
    //拼接
    e.mkString(" and ")                           //> res18: String = 1 and 2 and 7 and 9
    e.mkString("<", ",", ">")                     //> res19: String = <1,2,7,9>

多维数组定义:在一维数组的基础添加多维数组,数组中包含数组

    //多维数组
    //数组中添加一维数组
    val matrix = Array.ofDim[Double](3, 4)
                                                  //> matrix  : Array[Array[Double]] = Array(Array(0.0, 0.0, 0.0, 0.0), Array(0.0
                                                  //| , 0.0, 0.0, 0.0), Array(0.0, 0.0, 0.0, 0.0))
    matrix(2)(1) = 110
    matrix                                        //> res20: Array[Array[Double]] = Array(Array(0.0, 0.0, 0.0, 0.0), Array(0.0, 0
                                                  //| .0, 0.0, 0.0), Array(0.0, 110.0, 0.0, 0.0))
    
   val triangle = new Array[Array[Int]](10)      //> triangle  : Array[Array[Int]] = Array(null, null, null, null, null, null, n
                                                  //| ull, null, null, null)
   for (i <- 0 until triangle.length)
   triangle(i) = new Array[Int](i + 1)
   triangle                                       //> res21: Array[Array[Int]] = Array(Array(0), Array(0, 0), Array(0, 0, 0), Arr
                                                  //| ay(0, 0, 0, 0), Array(0, 0, 0, 0, 0), Array(0, 0, 0, 0, 0, 0), Array(0, 0,
                                                  //| 0, 0, 0, 0, 0), Array(0, 0, 0, 0, 0, 0, 0, 0), Array(0, 0, 0, 0, 0, 0, 0, 0
                                                  //| , 0), Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0))

Map、Tuple、Zip实战解析

Map实战:主要包括Map不可变(immutable)、Map可变(mutable)、getOrElse方法、map的真删改、排序等

  //map 不可变
  val map = Map("book"->10,"gun"->18,"ipad"->1000)//> map  : scala.collection.immutable.Map[String,Int] = Map(book -> 10, gun -> 1
                                                  //| 8, ipad -> 1000)
  for((k,v) <- map) yield (k,v * 0.9)             //> res0: scala.collection.immutable.Map[String,Double] = Map(book -> 9.0, gun -
                                                  //| > 16.2, ipad -> 900.0)
  //Map 可变
  val scores = scala.collection.mutable.Map("Scala" -> 7, "Hadoop" -> 8, "Spark" -> 10 )
                                                  //> scores  : scala.collection.mutable.Map[String,Int] = Map(Hadoop -> 8, Spark 
                                                  //| -> 10, Scala -> 7)
  //Map中getOrElse方法判断是否有key,如果flase就为后面value
  val hadoopScore = scores.getOrElse("Hadoop", 0) //> hadoopScore  : Int = 8
  //向Map中添加数值
  scores += ("R" -> 9)                            //> res1: com.dt.zhangsh.scala.ScalaOpWorkSheet.scores.type = Map(Hadoop -> 8, R
                                                  //|  -> 9, Spark -> 10, Scala -> 7)
  //删除
  scores -= "Hadoop"                              //> res2: com.dt.zhangsh.scala.ScalaOpWorkSheet.scores.type = Map(R -> 9, Spark 
                                                  //| -> 10, Scala -> 7)
  //排序
  val sortedScore = scala.collection.immutable.SortedMap("Scala" -> 7, "Hadoop" -> 8, "Spark" -> 10 )
                                                  //> sortedScore  : scala.collection.immutable.SortedMap[String,Int] = Map(Hadoop
                                                  //|  -> 8, Scala -> 7, Spark -> 10)

 


Tuple实战:tuple最主要是自动识别变量类型,遍历时从1开始,可以用空格或者点加占位符进行数据访问,截取大写字母后拼接以及获得tuple中的部分数据,不需要的用占位符代替

   //tuple主要是能够自动识别变量类型,自己查看类型
  val tuple =(1,2,3.14,"Rocky","Spark")           //> tuple  : (Int, Int, Double, String, String) = (1,2,3.14,Rocky,Spark)
  //遍历时从1开始,可以是空格或者加占位符序列进行访问
  val third = tuple._3                            //> third  : Double = 3.14
  //可以把tuple给一变量,如果只需一部分,其他的用占位符代替
  val (first,second,thirda,fourth,fifth) = tuple  //> first  : Int = 1
                                                  //| second  : Int = 2
                                                  //| thirda  : Double = 3.14
                                                  //| fourth  : String = Rocky
                                                  //| fifth  : String = Spark
  val (f, s, _, _, _) = tuple                     //> f  : Int = 1
                                                  //| s  : Int = 2
   //截取大写字母后拼接
  "Scala Spark".partition(_.isUpper)              //> res3: (String, String) = (SS,cala park)

Zip操作实战:按照两个数组的序列进行匹配组成心得元素

//Zip实战:包括按照序列进行匹配为元素
  val symbols = Array("[", "-", "]")              //> symbols  : Array[String] = Array([, -, ])
  val counts = Array(2,5,2)                       //> counts  : Array[Int] = Array(2, 5, 2)
  val pairs = symbols.zip(counts)                 //> pairs  : Array[(String, Int)] = Array(([,2), (-,5), (],2))
  
  for ((x,y) <- pairs) println(x*y)               //> [[
                                                  //| -----
                                                  //| ]]

Scala类的属性和对象私有字段实战详解

Scala类的使用实战:Scala类中变量必须赋值并且方法变量的时候用的还方法访问(def b_)
getter与setter实战:getter与setter方法只有是普通变量就行了
对象私有属性实战:使用private修饰的变量可以getter,没有setter,private[this]只能在本类中使用

class People {
  //定义的变量 必须赋值,只有不为private变量,它就用于setter和getter方法
  var age =0
  def increment() {age +=1}
  def current = age
}

class Student{
  //私有的变量只有getter方法没有setter方法
  private var privateAge = 0
  //private[this]修饰的变量只能当前类使用
  private[this] val name = "Scala"
  def age = privateAge  
  
  def isYounger(other: Student) = privateAge < other.privateAge
}

object HelloOOP{
  def main(args: Array[String]): Unit = {
    val people=new People
    people.age =10
//        people.increment()
//        people.increment()
//        println(people.current)
//    
//    val student = new Student
//    //student.age=10//私有的不能设置值 
//    println(student.age)
    
//    val student = new Student
//    println(student.name)    
  }
}

Scala主构造器、私有构造器、构造器重载实战详解

Scala主构造器实战:Scala类中可以添加参数的,主构造器就是默认的构造器

私有构造器实战 :主构造器重构必须集成主构造器!

构造器重载实战:如果Scala类是私有的,者不能被实例化,只有重构构造器才能使用

object ScalaOOP {
  def main(args: Array[String]): Unit = {
    
//    val p = new Teacher
//    p.name = "Spark"
//   
//    p.sayHello    
//    val p = new Teacher("Spark", 5)
//    println(" : " + p.age)
    val p = new Teacher("Spark", 5 , "male")
    println(" : " + p.age)
  }
}
//class Teacher {
//  var name : String = _
//  private var age = 27
//  private[this] val gender = "male"
//  
//  def this(name:String){
//    this
//    this.name = name
//  }
//    
//  def sayHello(){
//    println(this.name + ":" + this.age + " : " + this.gender)
//  }
//}
//如果Scala类是私有的,者不能被实例化,只有重构构造器才能使用
class Teacher private (val name : String, val age : Int){
  println("This is the primary constructor!!!")
  var gender : String = _
  println(gender)
  def this(name : String, age : Int, gender : String){
    this(name, age)
    
    this.gender = gender
  }
}

 未完待续。。。。。

posted on 2015-07-26 23:04  遗失の驿站  阅读(651)  评论(1编辑  收藏  举报

导航