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


Scala map()用法及代碼示例

Scala中的集合是一種數據結構,其中包含一組對象。集合的示例包括數組,列表等。我們可以使用幾種方法對這些集合進行一些轉換。 Scala提供的一種此類廣泛使用的方法是map()。有關map()方法的要點:

  • map()是高階函數。
  • 每個集合對象都有map()方法。
  • map()將某些函數用作參數。
  • map()將函數應用於源集合的每個元素。
  • map()返回與源集合類型相同的新集合。

用法

collection = (e1, e2, e3, ...)

//func is some function
collection.map(func)

//returns collection(func(e1), func(e2), func(e3), ...)

例子1:使用用戶自定義函數

// Scala program to 
// transform a collection 
// using map() 
  
//Creating object 
object GfG 
{ 
  
    // square of an integer 
    def square(a:Int):Int 
    =
    { 
        a*a 
    } 
  
    // Main method 
    def main(args:Array[String]) 
    { 
        // source collection 
        val collection = List(1, 3, 2, 5, 4, 7, 6) 
      
        // transformed collection 
        val new_collection = collection.map(square) 
  
        println(new_collection) 
  
    } 
  
}
輸出:
List(1, 9, 4, 25, 16, 49, 36)

在上麵的示例中,我們將用戶定義的函數平方作為參數傳遞給map()方法。創建一個新集合,其中包含原始集合的元素的平方。源集合不受影響。



例子2:使用匿名函數

// Scala program to 
// transform a collection 
// using map() 
  
//Creating object 
object GfG 
{ 
      
    // Main method 
    def main(args:Array[String]) 
    { 
        // source collection 
        val collection = List(1, 3, 2, 5, 4, 7, 6) 
  
        // transformed collection 
        val new_collection = collection.map(x => x * x ) 
  
        println(new_collection) 
    } 
}
輸出:
List(1, 9, 4, 25, 16, 49, 36)

在上麵的示例中,將匿名函數作為參數傳遞給map()方法,而不是為平方運算定義整個函數。這種方法減少了代碼大小。




相關用法


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