Scala Collection Method

  • 接收一元函数

    • map 转换元素,主要应用于不可变集合

      (1 to 10).map(i => i * i)
      (1 to 10).flatMap(i => (1 to i).map(j => i * j))
      
    • transformmap 相同,不过用于可变集合,直接转换

      ArrayBuffer("Peter", "Paul", "Mary").transform(_.toUpperCase)
      
    • collect 接收偏函数(PartialFunction)作为参数;模式匹配也是一种偏函数

      "-3+4".collect {
      	case '+' => 1 ; 
      	case '-' => -1 
      } // Vector(-1, 1)
      
    • groupBy 按指定函数分组,返回 Map

      val words = Array("Abc", "ab")
      val map = words.groupBy(_.substring(0, 1).toUpperCase)
      // Map(A -> Array(Abc, ab))
      
  • 接收二元函数

    • reduceLeft 从左向右规约 f(f(f(a, b), c), d)
      List(1, 7, 2, 9).reduceLeft(_ - _)
      // ((1 - 7) - 2) - 9 = 1 - 7 - 2 - 9 = -17
    
    • reduceRight 从右向左规约 f(a, f(b, f(c, d)))

      List(1, 7, 2, 9).reduceRight(_ - _)
      // 1 - (7 - (2 - 9)) = 1 - 7 + 2 - 9 = -13
      
    • foldLeft 提供初始值+二元函数,从左向右折叠,每次计算结果在左侧

      • 可用 /:(表示树形左侧)操作符表示,(init /: collection)(function)
    • foldRight 提供初始值+二元函数,从右向左折叠,每次计算结果在右侧

      • 可用 :\(表示树形右侧)操作符表示,(collection :\ init)(function)
      List(1, 7, 2, 9).foldLeft(0)(_ - _)  
      (0 /: List(1, 7, 2, 9))(_ - _)
      // 0 - 1 - 7 - 2 - 9 = -19
      
    • scanLeftscanRight 结合了 folding 和 mapping,结果为所有的中间过程值

      (1 to 10).scanLeft(0)(_ + _) // Vector(0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55)
      
  • zip 拉链,即将两个集合各个元素像拉链一样交叉结合在一起

    List(1,2,3) zip List("a","b","c") // List((1,a), (2,b), (3,c))
    
    • 长度不一致的集合则以较小的长度为准
  • zipAll 为长度较短的集合设置默认值,

    this.zipAll(that, thisDefault, thatDefault)
    
  • zipWithIndex 返回元素及对应的下标

    "Scala".zipWithIndex
    //  Vector((S,0), (c,1), (a,2), (l,3), (a,4))
    
  • view 为集合创建延迟视图

     val lazyView = (1 to 1000000).view
     lazyView.take(100).last //100
    
    • 对视图的操作都不会立即计算(包括第一个元素也不会)
    • Stream 不同,不会缓存任何值
    • apply 方法会强制计算整个视图,使用 lazyView.take(i).last 代替 lazyView(i)
  • par 并行化集合,后续应用的方法都会并发计算

    for (i <- (0 until 100).par) print(s" $i")
    // 1-99
    
    • 很好的解决并发编程问题

    • 将集合变为对于的并行化实现

    • 对于产生的结果,与串行方式的结果一致 (如 for...yield...

    • 可使用 seqtoArray 等方法将集合还原

    • 部分方法不能并发操作

      • 使用 reduce 替代 reduceLeft,先对各部分集合操作,然后聚合结果,但操作必须满足结合律
      • 使用 aggregate 替代 foldLeft,先对各部分集合操作,然后用另一个操作将结果聚合
          str.par.aggregate(Set[Char]())(_ + _, _ ++ _)
          // 等价于
          str.foldLeft(Set[Char]())(_ + _)
          ```
posted @ 2019-10-02 11:08  afewnotes  阅读(119)  评论(0编辑  收藏  举报