Scala学习 --------- Iterable常用方法
因为Iterable是所有集合的父类,所以其方法在所有集合中都适用
4.6.1 sum/max/min/count
sum/max/min
count统计偶数的个数
4.6.2 filter过滤
4.6.3 flatten 扁平化处理
扁平化处理:集合中的元素如果是多个集合,则将多个集合拆解成一个集合。
案例:
4.6.4 diff/intersect/union集合之间的操作
差集、交集和并集
diff差集
intersect交集
union并集(不去重)
4.6.5 map
语义:对集合中每个元素操作,返回一个新的集合
4.6.6 flatMap
语义:flatMap等价先map处理在flatten处理
4.6.7 zip拉链操作
4.6.8 forall对整个集合进行条件检查
4.6.9 partition对集合进行分组
4.6.10 reduce/reduceLeft/reduceRight 聚合
a)、reduce聚合函数的用法
注意:带有两个参数的函数,作为值传入reduce方法中的语法要点:
如:val sum=array.reduce((x,y)=>{x+y})
第一个参数x:代表后面函数体计算后的结果,
第二个参数y:代表集合中下一个元素
b)、reduceLeft聚合函数的用法
注意:1、reduceLeft和reduce计算方法是一样的
2、算法是外部左往右聚合,内部左往右计算
c)、reduceRight聚合函数的用法
注意:算法是外部右往左聚合,内部左往右计算
4.6.11 fold/foldLeft/foldRight 聚合
方法fold与reduce工作方法很象,但是它让你指定一个值,作为第一个元素
fold方法
foldLeft方法
foldRight方法
4.6.12 groupBy/grouped 分组函数
groupBy :返回一个新的Map集合,Map的key是分组的标准,value是对与标准相同的值进行归并
grouped :根据给定的长度n,进行分组。每n个元素分为一组。
演示案例:wordcount统计