scala之-集合类常用的高阶函数汇总map reduce flatMap fold scan union zip

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))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值