zoukankan      html  css  js  c++  java
  • scala 数据结构(八 ):-map映射操作

    在Scala中可以通过map映射操作来解决:

    将集合中的每一个元素通过指定功能(函数)映射(转换)成新的结果集合这里其实就是所谓的将函数作为参数传递给另外一个函数,这是函数式编程的特点

    以HashSet为例说明

    def map[B](f: (A) ⇒ B): HashSet[B] //map函数的签名

    1)这个就是map映射函数集合类型都有

    2)[B] 是泛型

    3)map 是一个高阶函数(可以接受一个函数的函数,就是高阶函数),可以接收 函数 f: (A) => B 后面详解(先简单介绍下.)

    4) HashSet[B] 就是返回的新的集合

    2 深刻理解map映射函数的机制-模拟实现

     def main(args: Array[String]): Unit = {
    
        val list1 = List(3, 5, 7)
        def f1(n1: Int): Int = {
          println("xxx")
          2 * n1
        }
        val list2 = list1.map(f1)
        println(list2)
    
        val myList = MyList()
        val myList2 = myList.map(f1)
        println("myList2=" + myList2)
        println("myList=" + myList.list1)
        
      }
    class MyList {
      var list1 = List(3, 5, 7)
      var list2 = List[Int]()
      def map(f:Int=>Int): List[Int] = {
        for (item<-list1) {
          list2 = list2 :+ f(item)
        }
        list2
      }
    }
    object MyList {
      def apply(): MyList = new MyList()
    }

    3  flatmap映射:flat即压扁,压平,扁平化映射

    flatmap:flat即压扁,压平,扁平化,效果就是将集合中的每个元素的子元素映射到某个函数并返回新的集合。

    看一个案例:
    val names = List("Alice", "Bob", "Nick")
    def upper( s : String ) : String = {
        s. toUpperCase
    }
    //注意:每个字符串也是char集合
    println(names.flatMap(upper)) 
  • 相关阅读:
    开启和禁用Wifi热点命令
    C# IE代理操作
    Asp.net QueryString批量插入和更新
    Asp.net 插入或更改查询字符串
    C#如何判断线程池中所有的线程是否已经完成之Demo
    mysql 安装及设置密码
    c# iis回收应用程序池
    判断是否为移动端
    rtmp,m3u8 直播地址
    byte数组转换为字符串
  • 原文地址:https://www.cnblogs.com/qiu-hua/p/13264426.html
Copyright © 2011-2022 走看看