Scala_day2

package com.song.scala.day02

import scala.collection.mutable

object Test02 {
  def main(args: Array[String]): Unit = {
    val arrs = Array(1, 23, 4, 5)
    val arrmap = arrs.map(x => x)
    println(arrmap.toBuffer)
    arrmap.foreach(println)
    /*
    集合:是一種用來存儲各種數據的容器
    scala集合可以分爲可變和不可變的集合,不可變集合可以安全的併發方法
    可變集合可以在適當的地方被更新或擴展。這意味着可以修改,添加 移除一個集合的元素
    不可變集合,相比之下,永遠不會改變。不過你仍然可以模擬添加,移除或更新操作。但是這些操作將在每一種情況下都返回一個新的集合,同時是原來的集合不會發生改變
     scala集合兩個主要的包:
     不可變集合:scala.collention.immutable
     可變集合:scala.collection.mutable,scala默認採用不可變集合
     scala的集合有三大類:序列Seq,集Set,映射Map,所有的集合都擴展自iterable特質

     */


    //數組
    //    數組元素要求類型一致
    //定長數組,數組不可擴容
    //變長數組,數組可擴容
    val array = new Array(4) //長度
    val arr = Array(1, 2, 3)

    //變長數組需引入包
    import scala.collection.mutable.ArrayBuffer
    val muta = ArrayBuffer[Int]()
    muta.append(1)
    muta += 3
    muta += (6, 2)
    muta.insert(34, 45) //第一個爲下標
    muta.remove(0, 2) //0開始移除兩個

    //yield 將函數的返回值封裝其他類型
    val res = for (i <- muta if i % 2 == 0) yield i * 10

    muta.filter(x => x % 2 == 0).map(x => x * 10)

    //paixu
    muta.sortWith((x, y) => x < y)
    muta.sortWith(_ > _)
    muta.sortBy(x => x)

    val arr4 = Array(("a", 3), ("b", 1), ("c", 2))
    val sotedArr = arr4.sortBy(_._2) //按第二個元素排序
    val sortedarr = arr4.sortWith(_._2 > _._2)
    println(sortedarr.toBuffer)
    //映射(Map) (重要)
    //    在scala中,把哈希表這種數據結構叫做映射
    //    scala中的Map存儲的內容是鍵值對(key-value),Scala中不可變的map是有序的,可變的的Map是無序的
    //    Scala,有可變Map(scala,collection,mutable,Map)和不可變Map(scala.collection.immutable.Map)
    //構建映射
    //    在Scala中,有兩種Map,一個是Immutable包下的Map,該MAP中的內容不可變,另一個是mutable包下的Map,該Map下的內容可變

    val user = Map(("tim", 4), ("herry", 8), ("shuke", 5))
    val godden = Map(("tim" -> 4), ("herry" -> 8), ("shuke" -> 5))

    //可變的
    import scala.collection.mutable.Map
    val god = Map(("tim" -> 4), ("herry" -> 8), ("shuke" -> 5))
    god += ("beta" -> 4, "tik" -> 9)
    //刪除
    god -= ("beta")
    god.remove("tik")
    //遍歷
    for ((key, value) <- god) println(key + "---------" + value)
    for (v <- god.values) println("---------" + v)
    for ((key, value) <- god) yield (key, value) //yield 封裝前面的值
    new mutable.LinkedHashMap[String, Int]

    //元組
    val tup = ("fdsf", true)
    tup._1 //元組是從1開始的
    //元組的聲明的第二種方式
    val tup1 = new Tuple1(3) //1是一種類型

    /*val tup,(a,b,c)=(1,2,3)
    //取值
    a
     */
    val str = tup.toString()
    tup.swap //交換兩個數字的位置

    //拉鍊操作
    val arr1 = Array(53, 56, 78)
    val arr2 = Array(34, 54, 22)
    //    arr1 zip  arr2      //長度較長的直接截掉
    //  (arr1 zip  arr2).map(x=>x._1+x._3)  //將zip後的數據add


    //    List列表:可變和不可變
    //    一個列表要麼爲空,要麼爲head元素加tail的列表
    val seq = Seq(1, 2, 3, 4)
    val list = Seq(43, 4, 7)
    //加進去
    8 :: List(3, 4)
    3 :: 5 :: Nil //Nil爲空的列表,所以會生成一個列表
    //加新的元素
    seq :+ Array(3, 4, 6)
    //將另一個list加入另一個
    val ints = List(34, 45, 75)
    val lists = list ++ seq

  //可變的
    import  scala.collection.mutable.ListBuffer
    val listb=ListBuffer[Int]()
    listb+=1
    listb+=2
    //聲明2
    var listb2 = new ListBuffer[Int]
    listb2.append(34)

    //list加到另一個list2
    list++listb2  //生成一個新的列表
    //後面追加
    listb2:+=5

    //set 無序 不重複  可變不可變

    //不可變
    val set=Set(3,43,5)
    //加數據
    set+56
    val set1=Set(56,78,97)
    set++set1
    set.getClass  //返回什麼類型
    //可變的
    val set2 = new mutable.HashSet[Int]()
    set2+=45
    set2+=455
    set2-=45
    set2.remove(455)

    //intersect  diff  union  並交差





  }

  def m1(x: Int): Int = {
    //方法中,會將最後一行代碼的值最爲返回,但是,如果賦值的過程,是不能作爲返回值
    val sum = x * x
    sum

  }


}

懶加載 java and scala

package com.song.scala.day02;

/**
 * 一般是單例模式的懶漢模式
 */
public class LazyDemo {
    private static MyProperty prop;

    public static MyProperty getProp() {
        if (prop == null) {
            prop = new MyProperty();
            System.out.println("getProperty"+prop);
        }
        return prop;
    }

    public static void main(String[] args) {


    }
}

class MyProperty {

}
package com.song.scala.day02

class  ScalazyDemo{

}
object ScalazyDemo1 {

  def init():Unit={
    println("init")
  }

  def main(args: Array[String]): Unit = {
    val  prop=init(); //沒有使用lazy修飾符

    println("after init")

    println(prop)

  }
}


object ScalazyDemo2 {

  def init():Unit={
    println("init")
  }

  def main(args: Array[String]): Unit = {
     lazy val  prop=init(); //沒有使用lazy修飾符

    println("after init")  //第一步執行

    println(prop)

  }
}

練習

package com.song.scala.day02

object test_2 {
  def main(args: Array[String]): Unit = {
    //創建一個List
    val list1 = List(1, 2, 3, 4, 5, 6, 8)

    //將list1中每個元素乘以二
    val list0 = list1.map(x => x * 2)

    //將list1中偶數取出形成新的集合
    val list2 = list1.filter(x => x % 2 == 0)

    //排序形成新的集合
    val list3 = list1.sorted //默認升序 降序reverse
    val list4 = list1.sortBy(x => x)
    val list5 = list1.sortWith((x, y) => x > y)
    //反轉排序
    val list6 = list1.sorted.reverse
    //將list1中的元素4個一組,類型爲Iterator
    val iterator: Iterator[List[Int]] = list1.grouped(4)
    //將iterator轉換爲list
    val list7: List[List[Int]] = iterator.toList
    //將多個list壓扁爲一個
    val list8=list7.reduce((x,y)=>x:::y)   //::: 表示兩個元素集合
    println(list8)
        //--reduce函數
    val flatten = list7.flatten
    println(flatten)

    //每個字符串按空格切分,再壓平

    val lines = List("hello tim  hello jerry", "Hello  suke hello")
    val wordsarr = lines.map(x=>x.split(" "))
  //  println(wordsarr.map(_.toBuffer))  //list裏有多個arrayBuffer,所以我們直接可以將切分的flatten
    val word = wordsarr.flatten
    println(word)
    //flatmap
    val word2=  lines.flatMap(x=>x.split(" "))  //先map再flat
    println(word2)
      
       //    ---------------------------------------------
    //並行計算求和     //併發:同一時間段
    val arr = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
    /* println(arr.sum)  //數組求和
     println(arr.reduce((x, y) => x + y))
     println(arr.reduce(_ + _))  //reduceleft  單線程操作
    */
    //    按照特定的順序
    println(arr.reduceLeft(_ + _))
    //多線程累加
    println(arr.par.reduce(_ + _)) //  想減時就結果不同了
    while (true) {
      val i: Int = 1                //根據線程數值也不一樣
      println((arr).reduce(_ - _))
    }

    //摺疊(fold):有初始值(無特定順序)
    println(arr.fold(0)(_ + _))   //第一參數 是初始值
    //摺疊:有初始值(有特定順序)
    arr.par.foldLeft(10)(_+_)   //當調用特定排序順序時,此時多線程不起作用

    //聚合
    val arr1=List(List(2,3,4),List(3,4,5),List(6,7,8))
    println(arr1.reduce((x, y) => List(x.sum + y.sum)))
    //  def aggregate[B](z : => B)(seqop : scala.Function2[B, A, B], combop : scala.Function2[B, B, B]) : B = { /* compiled code */ }
    /*
    第一參數代表初始值
    第二個參數列表的第一個參數,局部聚合(線程內聚合)
    第三個參數列表的第二個參數,全局聚合(線程間聚合)
     */
    val sum: Int = arr1.flatten.sum
     arr1.aggregate(0)(_+_.sum,_+_)  //初始值爲0

  //求聚合值,arr sum and   arr nums
    val arr2=Array(1,2,3,45,6,7)
    arr2.aggregate((0,0))  ((x,y)=>(x._1+y,x._2+1),  (m,n)=>(m._1+n._1,m._2+n._2))


  }

}

WordCount

package com.song.scala.day02

object WordCount {
  def main(args: Array[String]): Unit = {
    val lines = List("hello tim  hello jerry", "Hello  suke hello")
    //將數據切分,生成一個個單詞

    val word: List[String] = lines.flatMap(x => x.split(" "))

    //將空字符串過濾
    val words = word.filter(!_.isEmpty)
    //將每個單詞生成一個元組(word,1)
    val tuples: List[(String, Int)] = words.map((_, 1))

    //將相同的單詞進行分組
    val grouped: Map[String, List[(String, Int)]] = tuples.groupBy(_._1)
    //將相同單詞的數據進行個數統計
    //  val sumd: Map[String, Int] = grouped.map(x=>(x._1,x._2.size))
    val sumd = grouped.mapValues(_.size) //只操作value key留着呢
    println(sumd)

    //降序排序  map,list是沒有排序的方法的
    val sorted: List[(String, Int)] = sumd.toList.sortBy(_._2)
    println(sorted)


  }
}
 //一句代碼計數
lines.flatMap(_.split(" ")).filter(!_.isEmpty).map((_,1)).groupBy(_._1).mapValues(_.size).toList.sortBy(_._2)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章