带有示例的 Scala TreeSet map() 方法
map()方法用于通过将函数应用于给定 TreeSet 的所有元素来构建新的 TreeSet。
Method Definition: def map[B](f: (A) => B): TreeSet[B]
Return Type: It returns a new TreeSet containing all the elements after applying the given function.
示例 #1:
// Scala program of map()
// method
// Import TreeSet
import scala.collection.mutable._
// Creating object
object GfG
{
// Main method
def main(args:Array[String])
{
// Creating TreeSet
val q1 = TreeSet(1, 2, 3, 4, 5)
// Print the TreeSet
println(q1)
// Applying map method
val result = q1.map(x => x*x)
// Displays output
print("TreeSet with squared elements: " + result)
}
}
输出:
TreeSet(1, 2, 3, 4, 5)
TreeSet with squared elements: TreeSet(1, 4, 9, 16, 25)
示例 #2:
// Scala program of map()
// method
// Import TreeSet
import scala.collection.mutable._
// Creating object
object GfG
{
// Main method
def main(args:Array[String])
{
// Creating TreeSet
val q1 = TreeSet(1, 2, 3, 4, 5)
// Print the TreeSet
println(q1)
// Applying map method
val result = q1.map(x => x*x*x)
// Displays output
print("TreeSet with cubed elements: " + result)
}
}
输出:
TreeSet(1, 2, 3, 4, 5)
TreeSet with cubed elements: TreeSet(1, 8, 27, 64, 125)