map()方法用於通過將函數應用於此集合的所有元素來構建新集合。
函數定義: def map[B](f: (A) => B): immutable.Set[B]
返回類型: It returns a new set containing all the elements after applying the given function.
範例1:
// Scala program of map()
// method
// Creating object
object GfG
{
// Main method
def main(args:Array[String])
{
// Creating a set
val s1 = Set(5, 1, 3, 2, 4)
// Applying map method
val result = s1.map(x => x*x)
// Display output
println(result)
}
}
輸出:
Set(25, 1, 9, 16, 4)
範例2:
// Scala program of map()
// method
// Creating object
object GfG
{
// Main method
def main(args:Array[String])
{
// Creating a set
val s1 = Set(5, 1, 3, 2, 4)
// Applying map method
val result = s1.map(x => x/2)
// Display output
println(result)
}
}
輸出:
Set(2, 0, 1)
相關用法
- Scala Set ++()用法及代碼示例
- Scala Set &~()用法及代碼示例
- Scala Map last()用法及代碼示例
- Scala Int abs()用法及代碼示例
- Scala Set contains()用法及代碼示例
- Scala Set take()用法及代碼示例
- Scala Set sum()用法及代碼示例
- Scala Set min()用法及代碼示例
注:本文由純淨天空篩選整理自rupesh_rao大神的英文原創作品 Scala Set map() method with example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。