-
接收一元函式
-
map轉換元素,主要應用于不可變集合(1 to 10).map(i => i * i) (1 to 10).flatMap(i => (1 to i).map(j => i * j)) -
transform與map相同,不過用于可變集合,直接轉換ArrayBuffer("Peter", "Paul", "Mary").transform(_.toUpperCase) -
collect接收偏函式(PartialFunction)作為引數;模式匹配也是一種偏函式"-3+4".collect { case '+' => 1 ; case '-' => -1 } // Vector(-1, 1) -
groupBy按指定函式分組,回傳Mapval words = Array("Abc", "ab") val map = words.groupBy(_.substring(0, 1).toUpperCase) // Map(A -> Array(Abc, ab))
-
-
接收二元函式
reduceLeft從左向右規約f(f(f(a, b), c), d)
List(1, 7, 2, 9).reduceLeft(_ - _) // ((1 - 7) - 2) - 9 = 1 - 7 - 2 - 9 = -17-
reduceRight從右向左規約f(a, f(b, f(c, d)))List(1, 7, 2, 9).reduceRight(_ - _) // 1 - (7 - (2 - 9)) = 1 - 7 + 2 - 9 = -13 -
foldLeft提供初始值+二元函式,從左向右折疊,每次計算結果在左側- 可用
/:(表示樹形左側)運算子表示,(init /: collection)(function)
- 可用
-
foldRight提供初始值+二元函式,從右向左折疊,每次計算結果在右側- 可用
:\(表示樹形右側)運算子表示,(collection :\ init)(function)
List(1, 7, 2, 9).foldLeft(0)(_ - _) (0 /: List(1, 7, 2, 9))(_ - _) // 0 - 1 - 7 - 2 - 9 = -19 - 可用
-
scanLeft和scanRight結合了 folding 和 mapping,結果為所有的中間程序值(1 to 10).scanLeft(0)(_ + _) // Vector(0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55)
-
zip拉鏈,即將兩個集合各個元素像拉鏈一樣交叉結合在一起List(1,2,3) zip List("a","b","c") // List((1,a), (2,b), (3,c))- 長度不一致的集合則以較小的長度為準
-
zipAll為長度較短的集合設定默認值,this.zipAll(that, thisDefault, thatDefault) -
zipWithIndex回傳元素及對應的下標"Scala".zipWithIndex // Vector((S,0), (c,1), (a,2), (l,3), (a,4)) -
view為集合創建延遲視圖val lazyView = (1 to 1000000).view lazyView.take(100).last //100- 對視圖的操作都不會立即計算(包括第一個元素也不會)
- 與
Stream不同,不會快取任何值 apply方法會強制計算整個視圖,使用lazyView.take(i).last代替lazyView(i)
-
par并行化集合,后續應用的方法都會并發計算for (i <- (0 until 100).par) print(s" $i") // 1-99-
很好的解決并發編程問題
-
將集合變為對于的并行化實作
-
對于產生的結果,與串行方式的結果一致 (如
for...yield...) -
可使用
seq,toArray等方法將集合還原 -
部分方法不能并發操作
- 使用
reduce替代reduceLeft,先對各部分集合操作,然后聚合結果,但操作必須滿足結合律 - 使用
aggregate替代foldLeft,先對各部分集合操作,然后用另一個操作將結果聚合
str.par.aggregate(Set[Char]())(_ + _, _ ++ _) // 等價于 str.foldLeft(Set[Char]())(_ + _) ``` - 使用
-
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/1982.html
標籤:Scala
上一篇:Scala Operators, File & RegExp
下一篇:Scala XML
