下划线加角标(_1)元组中的元素角标是从1开始的
(3)将对偶的集合转换成为映射
val arr = Array(("a",88),("b",66))
arr.toMap
Array(("a",88),("b",66))位对偶的集合
toMap可以把对偶的集合转换成为映射
(4)拉链操作
val names = Array("a","b","c")
val s = Array(1,2,3)
val ns = names.zip(s)
ns: Array[(String, Int)] = Array((a,1), (b,2), (c,3))
将names的每一个元素和s中的每一个元素组成元组放入到Array中
16.集合
(1)创建一个不可变的集合
val lst1 = List(1,2,3)
(2)将0插入到lst1的前面生成一个新的List
val lst2 = 0 :: lst1
:: 操作符是将给定的头和尾创建一个新的列表
注意::: 操作符是右结合的,如9 :: 5 :: 2 :: Nil相当于 9 :: (5 :: (2 :: Nil))
(3)将一个元素添加到lst1的后面产生一个新的集合
val lst6 = lst1 :+ 3
(4)将2个list合并成一个新的List
val lst7 = lst1 ++ lst6
(5)将lst0插入到lst1前面生成一个新的集合
val lst9 = lst1.:::(lst0)
可变的序列
(1)构建一个可变列表,初始有3个元素1,2,3
val lst0 = ListBuffer[Int](1,2,3)
(2)向lst1中追加元素,注意:没有生成新的集合
lst1 += 4
lst1.append(5)
(3)将lst1中的元素最近到lst0中, 注意:没有生成新的集合
lst0 ++= lst1
17.Set
不可变的Set
(1)定义set
import scala.collection.immutable.HashSet
val set1 = new HashSet[Int]()
(2)将元素和set1合并生成一个新的set,原有set不变
val set2 = set1 + 4
可变的Set
(1)创建一个可变的HashSet
import scala.collection.mutable
val set1 = new mutable.HashSet[Int]()
(2)向HashSet中添加元素
set1 += 2
//add等价于+=
set1.add(4)
set1 ++= Set(1,3,5)
(3)删除一个元素
set1 -= 5
set1.remove(2)
18.Map
(1)创建一个map
import scala.collection.mutable
val map1 = new mutable.HashMap[String, Int]()
(2)向map中添加数据
map1("spark") = 1
(3)从map中移除元素
map1.remove("spark")
19.单词统计
val lines = List("hello tom hello jerry", "hello jerry", "hello kitty")
实现1:
lines.flatMap(.split(" ")).map((, 1)).groupBy(.1).mapValues(.foldLeft(0)(+_._2))
分析:
(1)lines.flatMap(_.split(" ")) 将集合中的单词进行压平,其中每个元素通过" "来切分
lines.flatMap(_.split(" "))后为
res17: List[String] = List(hello, tom, hello, jerry, hello, jerry, hello, kitty)
(2)lines.flatMap(.split(" ")).map((, 1))统计每一个单词出现的次数,出现一次计数1
执行后为
res18: List[(String, Int)] = List((hello,1), (tom,1), (hello,1), (jerry,1), (hel
lo,1), (jerry,1), (hello,1), (kitty,1))
(3).groupBy(_.1)将集合进行分组,分组是按照集合中每一个元组如(hello,1)的第一个单词(._1)进行分组
分组后为一个map:
res19: scala.collection.immutable.Map[String,List[(String, Int)]] = Map(tom -> L
ist((tom,1)), kitty -> List((kitty,1)), jerry -> List((jerry,1), (jerry,1)), hel
lo -> List((hello,1), (hello,1), (hello,1), (hello,1)))
(4).mapValues(.foldLeft(0)(+.2)) 获取map中的所有values如 List((tom,1)),foldLeft进行统计,(0)初始化参数为0,+._2进行求和,第一个_在循环时可能为初始化参数和进行求和后的值
执行后为:
res20: scala.collection.immutable.Map[String,Int] = Map(tom -> 1, kitty -> 1, je
rry -> 2, hello -> 4)
实现2:
lines.flatMap(.split(" ")).map((, 1)).groupBy(_._1).map(t=>(t._1, t.2.size)).toList.sortBy(._2).reverse