Scala Set map() 方法与示例
map()方法用于通过将函数应用于该集合的所有元素来构建新集合。
Method Definition: def map[B](f: (A) => B): immutable.Set[B]
Return Type: 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)