Hadoop & Spark學習筆記(三):Scala語言

安裝

sudo apt update
sudo apt install scala #安裝scala

基本

println("Hello World Scala!")   #列印一行文字
1+1 #整數相加
"A" + "1" + "B" #字串相加,scala必須用" "當成字串
1.toString + 1.toString #轉成字串再相加
"1".toInt + "2".toInt #轉成整數相加
"1".toFloat + "2".toFloat #轉成浮點數相加
var a = 5 #宣告變數
val b = 5 #宣告常數

資料集

不可變陣列Array
val arr1=new Array(5)
val arr2=new Array[Int](5)
val arr3=new Array[Float](5)
val arr4=Array(1,2,3,4,5)
val arr5=Array("A","B","C","D","E")
可變陣列
import scala.collection.mutable._
val arrBuff= ArrayBuffer(1,2,3)
可變陣列操作
arrBuff += 4 // 加入元素4
arrBuff -= 4 // 去掉元素4
arrBuff ++= Array(11,12,13,14,15) // 把不可變陣列併入到arrBuff
arrBuff.insert(0, 100,101,102) // 從0的索引位置插入100,101,102
arrBuff.remove(0, 3) // 從0的位置開始去除3個元素
arrBuff.trimEnd(5) // 去除arrBuff最後面的5個元素
不可變映射Map
val stdMap1=Map("ID01"->"曾子","ID02"->"子路","ID03"->"顏回","ID04"->"宰予","ID05"->"子貢")
stdMap1("ID01")
可變映射Map
val stdMap2= scala.collection.mutable.Map(1->"曾子",2->"子路",3->"顏回",4->"宰予",5->"子貢")
stdMap2(1)
stdMap2(1)="蘇秦"
stdMap2(1)
stdMap2 += (6->"子騫") // 增加一組映射關係
stdMap2 -= 2 // 把鍵為2個關係刪除
不可變List
val list1=List()
val list2=Nil
list1 == list2
val list3=List(6,7,8,9,10)
val list4=list3 :: 5
val list4=5 :: list3
val list5=1 :: 2 :: 3 :: 4 :: list4
list3.::(5)
list5.head
list5.tail
可變ListBuffer
val lstBuf=scala.collection.mutable.ListBuffer(1,2,3)
lstBuf += 4
lstBuf += (5,6)
val list1=List(7,8,9)
lstBuf ++= list1
lstBuf -= (4,5,6)
lstBuf --= list1
Range0~10
0 to 10
0.to(10)
val range1=Range(0, 10)
0~10或10~0,每次間隔2或-2
val range4=Range(0, 10, 2)
val range5=Range(10, 0, -2)
0~9
0 until 10

條件分支if

val x=2if(x % 2 == 0) println("x是偶數") else 
println("x是基數")
if(x % 2 == 0) {println("x是偶數")} else { println("x是基數")
}
if(x % 2 == 0) "x是偶數" else "x是基數"
val rlt1= if(x % 2 == 0) "x是偶數" else "x是基數"
val rlt2 = rlt1 + ",這是真的!"

迴圈

1加到10的總和,用while
var rlt=0
var i=1
while(i<=10){
rlt += i
i += 1
}
println(rlt)
用do while
var rlt=0
var i=1
do {
rlt += i
i += 1
} while(i<=10)
println(rlt)
用foreach加總
var rlt =0
(1 to 10).foreach(x=> rlt += x)
println(rlt)
for迴圈
var rlt1=0
for(i <- 1 to 10) rlt1 += i
println(rlt1)
雙層for迴圈
for(i<-1 to 2; j<-1 to 3){
println("第"+i+"章,"+"第"+j+"節")
}
訪問資料集
val arr5=Array("A","B","C","D","E")
for(c <- arr5) println(c)
for(c <- arr5 if c!="C") println(c)

函數

def printStar(x:Int) {
println("6" * x)
}
printStar(10)

常用資料集處理方法

val arr1=Array(1,2,3,4,5,6)
arr1.length
arr1.sum
arr1.max
arr1.min
arr1.last = arr1.head
arr1.init = arr1.tail
val arr2=Array(2,2,2,1,1,1,3,3,3)
val arr3=arr2.distinct #去除重複
val arr4=arr3.sortBy(x=>x) #排序
arr4.reverse #反向排序

Written by

Machine Learning / Deep Learning / Python / Flutter cakeresume.com/yanwei-liu

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store