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)
}
}
Scala函数式编程
最新推荐文章于 2024-07-21 07:09:13 发布