Spark学习记录(二)
三、集合深化
3.1、List
list数据处理方法:
- filter :过滤元素
- count :计算符合条件的元素个数
- map :对元素操作
- flatmap :压扁扁平,先map再flat
val site = "one" :: ("two" :: ("three" :: Nil)) var filterList = site.filter(x => x.length() > 2) filterList.foreach(println) var count = site.count(x => x.length() > 2) println(count) var nameList = List( "Hello michong", "Hello 米虫",
"Hello itekfly" ) var splitList: List[Array[String]] = nameList.map { x => x.split(" ") } var flatMapList: List[String] = nameList.flatMap(x => x.split(" ")) flatMapList.foreach(println) 可变长度List
import scala.collection.mutable.ListBuffer object Main { def main(args: Array[String]): Unit = { var listBuffer = ListBuffer[Int](1, 2, 3, 4, 5) listBuffer.append(6, 7, 8, 9) // 追加元素 listBuffer.+=(10) // 在后面追加元素 listBuffer.+=:(100) // 在前面追加元素 listBuffer.foreach(println) } } 3.2、Set
set是没有重复的对象集合,所有的元素都是唯一的
- 1. 交集: intersect , &
- 2. 差集: diff , &~
- 3. 子集: subsetOf
- 4. 最大: max
- 5. 最小: min
- 6. 转成数组: toList
- 7. 转成字符串: mkString
3.3、Map
map中元素的基本操作
// 初始化map
var map1: Map[String, Int] = Map( "one" -> 1, "two" -> 2 ) // 增加map的元素
map1 += ("three" -> 3) // 删除map中的元素
// map1.removed("three") // 方式1
map1 -= ("three") // 方式2
// 遍历方式1
for (map <- map1) { println("key: ", map._1, " value: ", map._2) } // 遍历方式2
map1.foreach(f => { println("key:" + f._1 + " ,value:" + f._2) }) // 合并map
var map2: Map[String, Int] = Map( "four" -> 4, "five" -> 5 ) map1.++(map2).foreach(println) Map处理数据的方法
- filter :过滤,留下符合条件的记录
- count :统计符合条件的记录数
- contains : map 中是否包含某个 key
- exist :符合条件的记录存在与否
println(map1.count(_._2.equals(1))) map2.filter(_._2.equals(5)).foreach(println) println(map2.contains("four")) println(map2.exists(_._1.equals("five"))) 3.4、元组
和列表类似,但是元组可以将不同的元素包含在内。
// 创建元组 var tuple = (1, 2, 3, 4, "one") println(tuple._4) // 遍历元组 var tupleIterator = tuple.productIterator while (tupleIterator.hasNext) { println(tupleIterator.next()) } // 转换为字符串 println(tuple.toString()) 3.5、Option
Option[T] 是一个类型为 T 的可选值的容器: 如果值存在, Option[T] 就是一个 Some[T] ,如果不存在, Option[T] 就是对象 None 。
def main(args: Array[String]): Unit = { // 初始化map
var map1: Map[String, Int] = Map( "one" -> 1, "two" -> 2 ) val value1: Option[Int] = map1.get("one") fun1(value1) } // 判断key是否存在
def fun1(value: Option[Int]) = { if (!value.isEmpty) { println("key存在,value为:", value.getOrElse())
} else { println("key不存在")
} } // 输出结果 (key存在,value为:,1)
四、偏函数
Scala中的Partia Function是一个Trait,其的类型为PartialFunction[A,B],其中接收一个类型为A的参数,返回一个类型为B的结果。
- 如果一个方法中没有 match 只有 case ,这个函数可以定义成 PartialFunction偏函数 。
- 偏函数定义时,不能使用括号传参,默认定义 PartialFunction 中传入一个值,匹配上了对应的case ,返回一个值,只能匹配同种类型。
- 一个 case 语句就可以理解为是一段匿名函数。
def main(args: Array[String]): Unit = { println(pf(1)) println(pf(6)) println(pf(true)) } def pf: PartialFunction[AnyVal, String] = { case 1 => "One" case 2 => "Two" case 3 => "Three" case i: Int => "Int" case i: Double => "Int" case _ => "Other" }#笔记#