當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Scala reduce()用法及代碼示例

reduce()方法是一個高階函數,它接受集合中的所有元素(數組,列表等),並使用二進製運算將它們組合以產生單個值。必須確保運算是可交換的和關聯的。匿名函數作為參數傳遞給reduce函數。句法:

val l = List(2, 5, 3, 6, 4, 7)
// returns the largest number from the collection
l.reduce((x, y) => x max y)

通過reduce方法選擇數字進行運算的順序是隨機的。這就是為什麽不優選非交換和非關聯運算的原因。例子:

// Scala program to 
// print maximum value 
// using reduce() 
  
// Creating object 
object GfG 
{ 
      
// Main method 
def main(args:Array[String]) 
{ 
    // source collection 
    val collection = List(1, 3, 2, 5, 4, 7, 6) 
  
    // finding the maximum valued element 
    val res = collection.reduce((x, y) => x max y) 
  
    println(res) 
} 
}

輸出:

7

在上述程序中,reduce方法選擇隨機對,並找出特定對中的最大值。再次將這些值相互比較,直到獲得單個最大值元素。在處理Spark中的彈性分布式數據集時,我們通常會同時使用reduce()方法和map()方法。 map()方法幫助我們將一個集合轉換為另一個集合,而reduce()方法則使我們能夠執行某些操作。

使用map()和reduce()查找平均值:
例:

// Scala program to 
// print average 
// using map() and reduce() 
  
//Creating object 
object GfG 
{ 
      
// Main method 
def main(args:Array[String]) 
{ 
    // source collection 
    val collection = List(1, 5, 7, 8) 
  
    // converting every element to a pair of the form (x,1) 
    // 1 is initial frequency of all elements 
    val new_collection = collection.map(x => (x,1)) 
  
    /* 
    List((1, 1), (5, 1), (7, 1), (8, 1)) 
    */
  
    // adding elements at correspnding positions 
    val res = new_collection.reduce( (a,b) => ( a._1 + b._1, 
                                            a._2 + b._2 ) ) 
    /* 
    (21, 4) 
    */
  
    println(res) 
    println("Average="+ res._1/res._2.toFloat) 
} 
}

輸出

(21, 4)
Average= 5.25

在上麵的程序中,集合的所有元素都被轉換為帶有兩個元素的元組。元組的第一個元素是數字本身,第二個元素是計數器。最初,所有計數器都設置為1。輸出本身是具有兩個元素的元組:第一個值是總和,第二個值是元素數。注意:reduce()方法給出的輸出類型與集合元素的類型相同。




相關用法


注:本文由純淨天空篩選整理自MohammadKhalid大神的英文原創作品 Scala | reduce() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。