Scala学习--函数式编程之集合操作

List

List代表一个不可变的列表
Liat的创建,val list = List(1,2,3,4)
List有head和tail,head代表List的第一个元素,tail代表第一个元素之后的所有元素,list.head,liat.tail
List有特殊的::操作符,可以用于将head和tail合并成一个List,0::list
如果一个List只有一个元素,那么它的head就是这个元素,它的tail是Nil

例如:用递归函数来给List中每个元素都加上指定前缀,并打印加上前缀的元素

def decorator(list:List[Int],prefix:String){
	if(list != Nil){
		println(prefix + list.head)
		decorator(list.tail,prefix)
	}
}

LinkedList

LinkedList代表一个可变的列表,使用elem可以引用其头部,使用next可以引用其尾部

案例1:使用while循环将列表中的每个元素都乘以2

val list = scala.collection.mutable.LinkedList(1,2,3,4)
var currentList = list
while(currentList != Nil){
	currentList.elem = currentList.elem * 2
	currentList = currentList.next
}

案例2:使用while循环将列表中每隔一个元素就乘以2

val list = scala.collection.mutable.LinkedList(1,2,3,4,5,6,7,8,9,10)
var currentList = list
var first = true
while(currentlList != Nil && currentList.next != Nil){
	if(first){currentList.elem = currentList.elem * 2;first = false}
	currentList = currentList.next.next
	currentList.elem = currentList.elem * 2
}

Set

set代表一个没有重复元素的集合
set是不保证插入顺序的,也就是说,set中的元素是乱序的

val s = new scala.collection.mutable.HashSet[Int]();s += 1;s += 2;s += 5

LinkedHashSet会用一个链表维护插入顺序

val s = new scala.collection.mutable.LinkedHashSet[Int]();i += 1;s += 2;s += 5

SortedSet会自动根据key来进行排序

val  s = new scala.collection.mutable.SortedSet("orange","apple","banana")

函数式编程

map案例:为List中每个元素都添加一个前缀

List("xiaoming","laowang","jack").map("name is " + _)   
输出:
name is xiaoming,name is laowang,name is jack

flatMap案例:将List中的多行句子拆分成单词

List("Hello world","You and me").flatMap(_.split(" "))
输出:
Hello,world,You,and,me

foreach案例:打印List中的每个单词

List("I","have","a","beautiful","hourse").foreach(println(_))
输出:
I
have
a
beautiful
hourse

zip案例:对学生姓名和成绩进行关联

List("xiaoming","laowang","jack").zip(List(100,95,61))
输出:
(xiaoming,100),(laowang,95),(jack,61)

综合案例:WorldCount统计两个文本单词个数

创建两个文本。
代码:

//使用Scala的io包将文本文件内的数据读取出来,并使用nkString转化成字符串
val lines1 = scala.io.Source.fromFile(E://test01.txt).mkString  
val lines2 = scala.io.Source.fromFile(E://test02.txt).mkString  
//使用List的伴生对象,将多个文件内的内容创建为一个List
val lines = List(lines1,lines2)

//下面这一行是核心代码,使用了多个高阶函数的链式调用,以及大量下划线。
spark本身提供的开发人员使用的编程api的风格,完全沿用了Scala的函数式编程,比如spark自身的api就提供了map,flatMap,reduce,foreach,以及更高级的reduceByKey,groupByKey等高阶函数

lines.flatMap(_.split(" ")).map((_.1)).map(_,_2).reduceLeft(_ + _)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值