Functional programming in Scala

1. traversing (the foreach)

method

foreach(f: (A) ⇒ Unit): Unit

Method Description

foreach API Explanation
parameter f: (A) ⇒ Unit Receiving a function object
function for the elements of the set of input parameters, return value is null
return value Unit air

The sample code

// 定义一个列表
 val a = List(1,2,3,4)
 //迭代打印
 a.foreach((x:Int)=>println(x))

Here Insert Picture Description

Type inference using simplified function definition

Using foreach to iterate over the list, and each element type in the list is determined

  • scala can be automatically inferred type of each element of the parameter set
  • When you create a function, type its parameter list can be omitted
The sample code
//定义一个列表
 val a = List(1,2,3,4)
 // 省略参数类型
 a.foreach(x=>println(x))

Here Insert Picture Description

Function definition to simplify the use of the underscore

  • When the function parameters, appear only once in the body of the function, and the function thereof is not nested calls, you may be used to simplify the function definition underscore
  • If the method parameter is a function, if appears underlined, Scala compiler automatically packaged into a code function
  • The parameter list is handled automatically by the compiler scala
The sample code
//定义一个列表
val a = List(1,2,3,4)
//使用下划线简化函数定义
a.foreach(println(_))

Here Insert Picture Description

2. Mapping (map)

When the calculated data is converted to a one data type to another data type of process, and therefore more mapping operation using the set of
map method of receiving a function, the function will be applied to each element, a return new list

method

def map[B](f: (A) ⇒ B): TraversableOnce[B]

Method Description

map method API Explanation
Generics [B] Specify the final map method returns a collection of generic
parameter f: (A) ⇒ B Passing a function object
that receives a function type A (to convert list element) and returns a value of type B
return value TraversableOnce [B] Set type B

The sample code

//1. 创建一个列表,包含元素1,2,3,4
val a = List(1,2,3,4)
//2. 对List中的每一个元素加1
a.map(x=>x+1)
//3.使用下划线来定义函数,对List中的每一个元素加1
a.map(_ + 1)

Here Insert Picture Description

3. Mapping flattening (flatMap)

definition

Can flatMap, understood as the first map, then flatten

  • The map is a list of the conversion element is a List
  • flatten flat and the whole list

method

def flatMap[B](f: (A) ⇒ GenTraversableOnce[B]): TraversableOnce[B]

Method Description

flatmap method API Explanation
Generics [B] The final set of element types to be converted
parameter f: (A) ⇒ GenTraversableOnce[B] 传入一个函数对象
函数的参数是集合的元素
函数的返回值是一个集合
返回值 TraversableOnce[B] B类型的集合

代码示例

//一个文本中包含了若干行,创建一个列表保存这若干行
//"hadoop hive spark flink flume", "kudu hbase sqoop storm"
//获取到文本中每一行中的每一个单词,并将每一个单词都放到列表中
// 定义文本行列表
val a = List("hadoop hive spark flink flume", "kudu hbase sqoop storm")
//使用map将文本行转换为单词数组
 a.map(x=>x.split(" "))
 // 将数组中的扁平化
 a.map(x=>x.split(" ")).flatten

Here Insert Picture Description

使用flatMap简化操作

代码示例
// 定义文本行列表
val a = List("hadoop hive spark flink flume", "kudu hbase sqoop storm")
//获取到文本中每一行中的每一个单词,并将每一个单词都放到列表中
a.flatMap(_.split(" "))

Here Insert Picture Description

4.过滤(filter)

过滤符合一定条件的元素

方法

def filter(p: (A) ⇒ Boolean): TraversableOnce[A]

方法说明

filter方法 API 说明
参数 p: (A) ⇒ Boolean 传入一个函数对象
接收一个集合类型的参数
返回布尔类型,满足条件返回true, 不满足返回false
返回值 TraversableOnce[A] 列表

代码示例

//1. 有一个数字列表,元素为:1,2,3,4,5,6,7,8,9  
//过滤出所有的偶数

 List(1,2,3,4,5,6,7,8,9).filter(_ % 2 == 0)

5.是否存在(exists)

方法

def exists(p: (A) ⇒ Boolean): Boolean

方法说明

对集合中的元素进行某个判断,其中之一符合条件则返回true,反之返回false

//1. 有一个数字列表,元素为:1,2,3,4,5,6,7,8,9  

//判断这个数字列表是否有小于 1 的存在
 List(1,2,3,4,5,6,7,8,9).exists(_ < 1)
 //判断这个数字列表是否有大于 1 的存在
 List(1,2,3,4,5,6,7,8,9).exists(_ > 5)

Here Insert Picture Description

6.排序(sorted、sortBy、sortWith)

在scala集合中,可以使用以下几种方式来进行排序

  • sorted默认排序
  • sortBy指定字段排序
  • sortWith自定义排序

默认排序(升序) (sorted)

代码示例
//1.定义一个列表,包含以下元素: 3, 1, 2, 9, 7
//2.对列表进行升序排序
List(3,1,2,9,7).sorted

Here Insert Picture Description

指定字段排序 (sortBy)

根据传入的函数转换后,再进行排序

方法
def sortBy[B](f: (A) ⇒ B): List[A]
方法说明
sortBy方法 API 说明
泛型 [B] 按照什么类型来进行排序
参数 f: (A) ⇒ B 传入函数对象
接收一个集合类型的元素参数
返回B类型的元素进行排序
返回值 List[A] 返回排序后的列表
代码示例
//1. 有一个列表,分别包含几行文本的内容:"01 hadoop", "02 flume", "03 hive", "04 spark"
//2. 请按照单词字母进行排序
val a = List("01 hadoop", "02 flume", "03 hive", "04 spark")
//按空格切分,以切分后的第二个元素进行排序
a.sortBy(_.split(" ")(1))

自定义排序 (sortWith)

自定义排序,根据一个函数来进行自定义排序

方法
def sortWith(lt: (A, A) ⇒ Boolean): List[A]
方法说明
sortWith方法 API 说明
参数 lt: (A, A) ⇒ Boolean 传入一个比较大小的函数对象
接收两个集合类型的元素参数
返回两个元素大小,小于返回true,大于返回false
返回值 List[A] 返回排序后的列表
代码示例
//1. 有一个列表,包含以下元素:2,3,1,6,4,5
val a = List(2,3,1,6,4,5)
//2. 使用sortWith对列表进行降序排序
a.sortWith((x,y) => if(x>y)true else false)
//函数参数只在函数中出现一次,可以使用下划线代替
a.sortWith(_ > _)

Here Insert Picture Description

7.分组(groupBy)

我们如果要将数据按照分组来进行统计分析,就需要使用到分组方法
groupBy表示按照函数将列表分成不同的组

方法

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

方法解析

groupBy方法 API 说明
泛型 [K] Type grouping field
parameter f: (A) ⇒ K A function object passing
the received parameter set element type
return type of a key K, this key will be used for grouping the same key in a group
return value Map[K, List[A]] Returns a mapping, K is the packet fields, List field in this packet to a corresponding set of data

The sample code

//有一个列表,包含了学生的姓名和性别(0代表男 1 代表女):  
//"zhangsan","0"   "lisi","1"  "wangwu","0"
//请按照性别进行分组,统计不同性别的学生人数

//定义一个元组列表来保存学生姓名和性别
val a = List("zhangsan"-> "0", "lisi"->"1", "wangwu"->"0")
//按照性别进行分组 
val b = a.groupBy(_._2)
// 将分组后的映射转换为性别/人数元组列表	
 b.map(x => x._1 -> x._2.size)

8. polymeric calculated (the reduce)

Polymerization operation, a list of data may be combined into one. Such operations are often used in statistical analysis
reduce shows a list, a function for passing aggregate calculations

  • ReduceLeft reduce and consistent results, showing left to right
  • reduceRight right-to-left calculation

method

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

Method Description

reduce method API Explanation
Generics [A1 >: A] (Lower bound) is a collection of element type A1 must subclass
parameter by: (A1, A1) ⇒ A1 Incoming function object, continuous polymerization operation for
the first type parameters A1: after the polymerization of the current variable
second parameter type A1: this element to be polymerised
return value A1 Final polymerization of a list element

The sample code

//定义一个列表,包含以下元素:1,2,3,4,5,6,7,8,9,10
val a = List(1,2,3,4,5,6,7,8,9,10)

// 第一个下划线表示第一个参数,就是历史的聚合数据结果
// 第二个下划线表示第二个参数,就是当前要聚合的数据元素
//使用reduce计算所有元素的和
a.reduce(_ + _)
// 与reduce一样,从左往右计算
a.reduceLeft(_ + _)
// 从右往左聚合计算
 a.reduceRight(_ + _)

Here Insert Picture Description

9. folding (fold)

fold and reduce like, but more than a specified initial value of the parameter

  • FoldLet and consistent fold effect, represents a calculation from left to right
  • calculated from right to left indicates foldRight

method

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

Method Description

reduce method API Explanation
Generics [A1 >: A] (Lower bound) is a collection of element type A1 must subclass
Parameter 1 z: A1 The initial value
Parameter 2 by: (A1, A1) ⇒ A1 Objects passed to the function, for continuous operation of folding
the first parameter is a type A1: current variable folded
second type A1 parameters: the current to be folded element
return value A1 The final list is a folded element

The sample code

//定义一个列表,包含以下元素:1,2,3,4,5,6,7,8,9,10
val a = List(1,2,3,4,5,6,7,8,9,10)
//使用fold方法计算所有元素的和
a.fold(0)(_ + _)
a.foldLeft(0)(_ + _)
a.foldRight(0)(_ + _)

Here Insert Picture Description

Published 88 original articles · won praise 114 · Views 2994

Guess you like

Origin blog.csdn.net/hongchenshijie/article/details/104022547