Scala SortedSet map()方法及示例
map() 方法被用来建立一个新的SortedSet,通过对这个SortedSet的所有元素应用一个函数。
方法定义: def map[B](f: (A) => B): immutable.SortedSet[B]
返回类型。它返回一个新的SortedSet,包含应用给定函数后的所有元素。
例子 #1:
// Scala program of map()
// method
import scala.collection.immutable.SortedSet
// Creating object
object GfG
{
// Main method
def main(args:Array[String])
{
// Creating a SortedSet
val s1 = SortedSet(5, 1, 3, 2, 4)
// Applying map method
val result = s1.map(x => x*x)
// Display output
println(result)
}
}
输出。
TreeSet(1, 4, 9, 16, 25)
例子#2。
// Scala program of map()
// method
import scala.collection.immutable.SortedSet
// Creating object
object GfG
{
// Main method
def main(args:Array[String])
{
// Creating a SortedSet
val s1 = SortedSet(5, 1, 3, 2, 4)
// Applying map method
val result = s1.map(x => x/2)
// Display output
println(result)
}
}
输出。
TreeSet(0, 1, 2)
极客教程