Scala之函数式编程(2)

1.排序

  • sorted默认排序 从小到大
scala> List(55,88,99,66,44).sorted
res2: List[Int] = List(44, 55, 66, 88, 99)
  • sortBy指定字段排序
    根据传入的函数转换后,再进行排序
方法:
def sortBy[B](f: (A) ⇒ B): List[A]

例子:
1.有一个列表,分别包含以下文本行:"01 hadoop", "02 flume", "03 hive", "04 spark"
2.请按照单词字母进行排序
scala> val a = List("01 hadoop", "02 flume", "03 hive", "04 spark")
a: List[String] = List(01 hadoop, 02 flume, 03 hive, 04 spark)

// 获取单词字段
scala> a.sortBy(_.split(" ")(1))      
res8: List[String] = List(02 flume, 01 hadoop, 03 hive, 04 spark)
  • sortWith自定义排序
    自定义排序,根据一个函数来进行自定义排序
def sortWith(lt: (A, A)Boolean): List[A]

案例:
1.有一个列表,包含以下元素:2,3,1,6,4,5
2.使用sortWith对列表进行降序排序

方法1: 

scala> val a = List(2,3,1,6,4,5)
a: List[Int] = List(2, 3, 1, 6, 4, 5)
​
scala> a.sortWith((x,y) => if(x<y)true else false)
res15: List[Int] = List(1, 2, 3, 4, 5, 6)
​
scala> res15.reverse
res18: List[Int] = List(6, 5, 4, 3, 2, 1)

//优化:一步一步简化案例,直至用下划线表示。
scala> val a = List(2,3,1,6,4,5)
a: List[Int] = List(2, 3, 1, 6, 4, 5)
val hs1=(x:Int,y:Int)=> if(x>y) true else false
a.sortWith(hs1)
a.sortWith((x:Int,y:Int)=> if(x>y) true else false)
a.sortWith((x,y)=> if(x>y) true else false)



// 函数参数只在函数中出现一次,可以使用下划线代替(函数式编程思想)
scala> a.sortWith(_ > _) 
res19: List[Int] = List(6, 5, 4, 3, 2, 1)

//在优化:一行搞定
List(2,3,1,6,4,5).sortWith(_ > _)

在这里插入图片描述

2.分组

**简介:**我们如果要将数据按照分组来进行统计分析,就需要使用到分组方法

定义
groupBy表示按照函数将列表分成不同的组

方法
def groupBy[K](f: (A) ⇒ K): Map[K, List[A]]

过程:
在这里插入图片描述
案例:

1.有一个列表,包含了学生的姓名和性别: 

"张三", "男"
"李四", "女"
"王五", "男"

2.请按照性别进行分组,统计不同性别的学生人数

scala> val a = List("张三"->"男", "李四"->"女", "王五"->"男")
a: List[(String, String)] = List((张三,), (李四,), (王五,))// 按照性别分组
scala> a.groupBy(_._2)    // _通配符  _N 访问第N个元素
res0: scala.collection.immutable.Map[String,List[(String, String)]] = Map(-> List((张三,), (王五,)),-> List((李四,)))// 将分组后的映射转换为性别/人数元组列表
scala> res0.map(x => x._1 -> x._2.size)   //第一个元素  在分组的基础上第二个元素的长度
res3: scala.collection.immutable.Map[String,Int] = Map(-> 2,-> 1)

在这里插入图片描述

3.聚合操作

reduce表示将列表,传入一个函数进行聚合计算

定义:
def reduce[A1 >: A](op: (A1, A1) ⇒ A1): A1

reduce和reduceLeft效果一致,表示从左到右计算
reduceRight表示从右到左计算

在这里插入图片描述

例子:
1.定义一个列表,包含以下元素:1,2,3,4,56,7,8,9,5,5,8
2.使用reduce计算所有元素的和

scala> val a = List(1,2,3,4,56,7,8,9,5,5,8)
a: List[Int] = List(1, 2, 3, 4, 56, 7, 8, 9, 5, 5, 8)
​
scala> a.reduce((x,y) => x + y)
res12: Int = 108// 第一个下划线表示第一个参数,就是历史的聚合数据结果
// 第二个下划线表示第二个参数,就是当前要聚合的数据元素
scala> a.reduce(_ + _)  //两个下划线代表两个参数
res12: Int = 108// 与reduce一样,从左往右计算
scala> a.reduceLeft(_ + _)
res12: Int = 108// 从右往左聚合计算
scala> a.reduceRight(_ + _)
res12: Int = 108

4. 折叠 fold

fold与reduce很像,但是多了一个指定初始值参数

定义
def fold[A1 >: A](z: A1)(op: (A1, A1) ⇒ A1): A1

案例
1.定义一个列表,包含以下元素:1,2,3,4,5,6,7,8,9,10
2.使用fold方法计算所有元素的和
参考代码
scala> val a = List(1,2,3)
a: List[Int] = List(1, 2, 3)
​
scala> a.fold(100)(_ + _)
res4: Int = 106

猜你喜欢

转载自blog.csdn.net/m0_49834705/article/details/112691463