• Scala 常用集合操作函数-map、reduce、fold、scan


    1.map映射

    //---------------映射---------------
    val data1 = List[String]("abc", "ade", "xyz")
    
    //map 映射
    val list1 = data1.map(data => data.toUpperCase)
    println(list1)  //List(ABC, ADE, XYZ)
    
    //flatMap 扁平化
    val list2 = data1.flatMap(data => data.toUpperCase)
    println(list2)  //List(A, B, C, A, D, E, X, Y, Z)
    
    //filter 过滤
    val list3 = data1.filter(data => data.startsWith("a"))
    println(list3)  //List(abc, ade)
    

    2.reduce归约

    //----------------reduce----------------
    //reduceLeft和reduce一样 求和,n1:结果;n2:当前元素。第一次的结果是第一个元素。
    val reduceLeftSum: Int = (1 to 5).reduceLeft((n1, n2) => n1 + n2)
    println(s"reduceLeftSum = ${reduceLeftSum}")  //15
    
    //reduceLeft 求最大值
    val reduceLeftMax: Int = (1 to 5).reduceLeft((n1, n2) => if (n1 > n2) n1 else n2)
    println(s"reduceLeftMax = ${reduceLeftMax}")  //5
    
    //reduceRight n1:当前元素;n2:结果。第一次的结果是第一个元素。
    //1-(2-(3-(4-5)))
    val reduceRightSub: Int = (1 to 5).reduceRight((n1, n2) => n1 - n2)
    println(s"reduceRightSub = ${reduceRightSub}")  //3
    

    3.fold折叠

    //左折叠左边的参数就是结果,右折叠右边的参数就是结果
    //-------------------fold-------------------
    //左折叠。加了一个类似于java8中reduce方法的identity初始值,初始值作为第一次的结果
    //案例1:将字符串中的字符添加到一个ArrayBuffer中
    val foldLeft1: mutable.Seq[Char] = "scala".foldLeft(ArrayBuffer[Char]())((buffer, c) => buffer += c)
    println(s"foldLeft1 = ${foldLeft1}")  //ArrayBuffer(s, c, a, l, a)
    //左折叠简写方式
    val foldLeft2: mutable.Seq[Char] = (ArrayBuffer[Char]() /: "scala") ((buffer, c) => buffer += c)
    println(s"foldLeft2 = ${foldLeft2}")  //ArrayBuffer(s, c, a, l, a)
    //案例2:统计字符串中字符的个数,保存在map中
    val foldLeft3: mutable.Map[Char, Int] = (mutable.Map[Char, Int]() /: "scala") ((map, c) => map += (c -> (map.getOrElse(c, 0) + 1)))
    println(s"foldLeft3 = ${foldLeft3}")  //Map(s -> 1, a -> 2, l -> 1, c -> 1)
    
    //右折叠
    val foldRightSub1: Int = (1 to 5).foldRight(998)((n1, n2) => n1 - n2)
    println(s"foldRightSub1 = ${foldRightSub1}")  //-995
    //右折叠简写方式
    val foldRightSub2: Int = ((1 to 5) : 998) ((n1, n2) => n1 - n2)
    println(s"foldRightSub2 = ${foldRightSub2}")  //-995
    

    4.scan扫描

    //左扫描保留折叠的中间结果,初始值也保存
    val scanLeft: immutable.Seq[Int] = (1 to 5).scanLeft(5)((n1, n2) => n1 - n2)
    //scanLeft = Vector(5, 4, 2, -1, -5, -10),左扫描的结果以左边为基点,不停添加到右边
    println(s"scanLeft = ${scanLeft}")
    
    //右扫描
    val scanRight = (1 to 5).scanRight(5)((n1, n2) => n1 - n2)
    //scanRight = Vector(-2, 3, -1, 4, 0, 5),左扫描的结果以右边为基点,不停添加到左边
    println(s"scanRight = ${scanRight}")
  • 相关阅读:
    Ubuntu
    SSH
    Markdown
    Mac OS 上的一些骚操作
    Linux Bash
    JConsole
    IDEA
    Groovy
    Github
    Git
  • 原文地址:https://www.cnblogs.com/noyouth/p/12745606.html
Copyright © 2020-2023  润新知