scala之-集合類常用的高階函數彙總map reduce flatMap fold scan union zip

2020-08-14 01:04:37

scala之-集合類常用的高階函數彙總

集合常用的高階函數有以下幾種:

  • map
  • flatmap
  • filter
  • reduce
  • fold
  • scan
  • union
  • zip

map

    val list = List(1, 2, 3)

    //map => List(2, 4, 6)
    val map: List[Int] = list.map(_ * 2)
    println(map)

flatMap

 //flatMap
    val flatmap: List[Int] = list.flatMap(i => List(i, 1))
    println(flatmap) //List(1, 1, 2, 1, 3, 1)

filter

   //filter
    val filter: List[Int] = list.filter(i => i - 1 > 0)
    println(filter) //List(2,3)

reduce 、reduceLeft、reduceRight

    //reduce
    val result: Int = list.reduceLeft(_ + _)
    val sum: Int = list.sum
    println(result,sum) //6

fold、foldLeft、foldRight

    //fold & product
    val fold: Int = list.fold(1)(_ * _)
    val product: Int = list.product
    println(fold, product)
      
    //foldLeft
    val s = "aaaaaabbbbbbccccc"
    val charToInt: Map[Char, Int] = s.foldLeft(Map[Char, Int]()) {
      (map, c) =>
        val oldValue: Int = map.getOrElse(c, 0)
        map.+((c, oldValue + 1)) 
    }
    //foldRight
    val charToInt1: Map[Char, Int] = s.foldRight(Map[Char, Int]()) {
      (c, map) =>
        val old: Int = map.getOrElse(c, 0)
        map.+((c, old + 1))
    }
    println(charToInt, charToInt1) //Map(a->6,b->6,c->5)

scan、scanLeft、scanRight

    //scan,scanLeft & scanRight差不多,只是運算順序不一樣
    val scan: List[Int] = list.scan(0)(_ + _)
    println(scan.mkString("-"))//0 - 1 - 3 - 6

union

    //union
    val union: List[Int] = list.union(list)
    println(union) //List(1,2,3,1,2,3)

zip

    //zip ,只能保留min(size)的數據,後面的數據會丟失的可能
    val tuples: List[(Int, Int)] = list.zip(list.map(_ * 2))
    println(tuples) //List((1,2),(2,4),(3,6))