Map mapping and flatMap mapping in scala

Map mapping: It is a typical transformation operation for a set, it maps each element in the set to a new result set through a specified function .
Let's take a look at using map mapping to solve a practical problem.
Please change all names in names1 = List("Tony","Tom","Mary") to uppercase, put the result in a new set and return, that is, return a new List(TONY, TOM, MARY)

object mapExer01 {
    
    
  def main(args: Array[String]): Unit = {
    
    
     //利用map映射将list1中的所有元素装换为大写
    val names1 = List("Tony","Tom","Mary","Jack")
    val names2 = names1.map(upperString)
    println(names2)

  }
  def upperString(s: String): String ={
    
    
    s.toUpperCase()
  }
}

The result is: List(TONY, TOM, MARY, JACK)

Here are a few explanations about the map mapping process:

  1. map is a higher-order function, which can receive a function (a function in scala can also be used as a parameter)
  2. Here we are passing the method, but it will be converted into a function
  3. Through the operation of map, return a new collection names2
  4. The bottom layer will traverse all the elements of names1 and pass it to upperString, encapsulate the result of upperString into a new collection and return
  5. The names1 collection itself has not changed

flatMap mapping: It is an extension of map mapping. In flatMap, we will pass a function, the function for each input will return a collection (instead of an element), and finally flatMap the final set of all flattened into a new collection.
For example, the original result of the following example should be List('T','O','N','Y'), List('T','O','M')..., and finally flatMap flattened into List( T, O, N, Y, T, O, M, M, A, R, Y, J, A, C, K)

object mapExer02 {
    
    
  def main(args: Array[String]): Unit = {
    
    
    /*
   flatmap映射:flat即压扁,压平,扁平化映射  即相当于将集合中的每一个元素都当作为一个新的集合,再次打散进行相应的操作
     */
    val names1 = List("Tony","Tom","Mary","Jack")
    val names2 = names1.flatMap(upperString)  //这里注意names1中的每个元素(字符串)也是一个集合
    println(names2)

  }
  def upperString(s: String): String ={
    
    
    s.toUpperCase()
  }

}

结果为:List(T, O, N, Y, T, O, M, M, A, R, Y, J, A, C, K)

Guess you like

Origin blog.csdn.net/weixin_44080445/article/details/109259498