Scala函数式编程

object FunctionTest {
  def main(args: Array[String]): Unit = {

    val ints = List(1, 2, 3, 4)

    // foreach(循环)
    ints.foreach(e => {
      println(e)
    })
    // 简化写法(当函数参数,只在函数体中出现一次,而且函数体没有嵌套调用时,可以使用下划线来简化函数定义)
    ints.foreach(println(_))

    // map(映射)
    val newMapList = ints.map(e => e + 1)

    // flatMap(将多个集合合并成一个)
    val flatMap = List("hadoop hive spark flink flume", "kudu hbase sqoop storm")
    val newFlatMapList = flatMap.flatMap(e => e.split(" "))
    // 简化写法
    flatMap.flatMap(_.split(" "))


    // filter(过滤)
    ints.filter(e => e % 2 == 0)
    ints.filter(_ % 2 == 0)

    // sorted(排序)
    ints.sorted
    // 按照某个字段排序
    val sortByField = List("01 hadoop", "02 flume", "03 hive", "04 spark")
    sortByField.sortBy(e => e.split(" ")(0))
    sortByField.sortBy(_.split(" ")(0))
    // 自定义排序
    val sortWithList = List(2,3,1,6,4,5)
    sortWithList.sortWith((x, y) => { x < y })
    // 简化写法
    sortWithList.sortWith(_ < _)

    // groupBy(分组)
    val groupByList = List("张三"->"男", "李四"->"女", "王五"->"男")
    groupByList.groupBy(e => e._2)
    groupByList.groupBy(_._2)

    // reduce(聚合)
    val reduceList = List(1,2,3,4,5,6,7,8,9,10)
    // 求和
    reduceList.reduce((x, y) => x + y)
    reduceList.reduce(_ + _)
    reduceList.sum

    // fold(设置初始值的reduce)
    val foldList = List(1,2,3,4,5,6,7,8,9,10)
    foldList.fold(10)(_ + _)


    println("=====================")
    // wordCount
    val strList = List("hadoop java hadoop hive hive hive scala scala")
    val wordList = strList.flatMap(_.split(" "))
    val wordListGroup = wordList.groupBy(word => word)
    val countMap = wordListGroup.map(e => {
      (e._1, e._2.length)
    })
    val result = countMap.toList.sortBy(_._2).reverse.take(3)
    println(result)

    // 简化
    strList
      .flatMap(_.split(" "))
      .groupBy(word => word)
      .map(e => (e._1, e._2.length))
      .toList.sortBy(_._2)
      .reverse
      .take(3)

  }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值