Scala map()方法
Scala中的集合是一种数据结构,它容纳了一组对象。集合的例子包括Arrays、Lists等。我们可以使用一些方法对这些集合进行一些转换。
关于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)
在上面的例子中,我们将一个用户定义的函数 square 作为参数传递给 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() 方法,而不是为方形操作定义一个完整的函数。这种方法减少了代码的大小。
极客教程