240520Scala笔记
第 7 章 集合
7.1 集合1 数组Array
集合(Test01_ImmutableArray):
package chapter07
object Test01_ImmutableArray {
def main(args: Array[String]): Unit = {
// 1. 创建数组
val arr: Array[Int] = new Array[Int](5)
// 另一种创建方式
val arr2 = Array(12, 37, 42, 58, 97)
println(arr)
// 2. 访问元素
println(arr(0))
println(arr(1))
println(arr(4))
// println(arr(5))
arr(0) = 12
arr(4) = 57
println(arr(0))
println(arr(1))
println(arr(4))
println("========================")
// 3. 数组的遍历
// 1) 普通for循环
for (i <- 0 until arr.length){
println(arr(i))
}
for (i <- arr.indices) println(arr(i))
println("---------------------")
// 2) 直接遍历所有元素,增强for循环
for (elem <- arr2) println(elem)
println("---------------------")
// 3) 迭代器
val iter = arr2.iterator
while (iter.hasNext)
println(iter.next())
println("---------------------")
// 4) 调用foreach方法
arr2.foreach( (elem: Int) => println(elem) )
arr.foreach( println )
println(arr2.mkString("--"))
println("========================")
// 4. 添加元素
val newArr = arr2.:+(73)
println(arr2.mkString("--"))
println(newArr.mkString("--"))
val newArr2 = newArr.+:(30)
println(newArr2.mkString("--"))
val newArr3 = newArr2 :+ 15
val newArr4 = 19 +: 29 +: newArr3 :+ 26 :+ 73
println(newArr4.mkString(", "))
}
}
不可变数组用 +: 或 :+ 追加元素 可变数组用 arr1.append(6) 追加元素
7.2 集合2
package chapter07
import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer
object Test02_ArrayBuffer {
def main(args: Array[String]): Unit = {
// 1. 创建可变数组
val arr1: ArrayBuffer[Int] = new ArrayBuffer[Int]()
val arr2 = ArrayBuffer(23, 57, 92)
println(arr1)
println(arr2)
// 2. 访问元素
// println(arr1(0)) // error
println(arr2(1))
arr2(1) = 39
println(arr2(1))
println("======================")
// 3. 添加元素
val newArr1 = arr1 :+ 15
println(arr1)
println(newArr1)
println(arr1 == newArr1)
val newArr2 = arr1 += 19
println(arr1)
println(newArr2)
println(arr1 == newArr2)
newArr2 += 13
println(arr1)
77 +=: arr1
println(arr1)
println(newArr2)
arr1.append(36)
arr1.prepend(11, 76)
arr1.insert(1, 13, 59)
println(arr1)
arr1.insertAll(2, newArr1)
arr1.prependAll(newArr2)
println(arr1)
// 4. 删除元素
arr1.remove(3)
println(arr1)
arr1.remove(0, 10)
println(arr1)
arr1 -= 13
println(arr1)
// 5. 可变数组转换为不可变数组
val arr: ArrayBuffer[Int] = ArrayBuffer(23, 56, 98)
val newArr: Array[Int] = arr.toArray
println(newArr.mkString(", "))
println(arr)
// 6. 不可变数组转换为可变数组
val buffer: mutable.Buffer[Int] = newArr.toBuffer
println(buffer)
println(newArr)
}
}
arr.toArray 变成不可变数组 newArr.toBuffer 变成可变数组
7.3 集合3
package chapter07
object Test03_MulArray {
def main(args: Array[String]): Unit = {
// 1. 创建二维数组
val array: Array[Array[Int]] = Array.ofDim[Int](2, 3)
// 2. 访问元素
array(0)(2) = 19
array(1)(0) = 25
println(array.mkString(", "))
for (i <- 0 until array.length; j <- 0 until array(i).length){
println(array(i)(j))
}
for (i <- array.indices; j <- array(i).indices){
print(array(i)(j) + "\t")
if (j == array(i).length - 1) println()
}
array.foreach(line => line.foreach(println))
array.foreach(_.foreach(println))
}
}
7.4 集合4 列表List
package chapter07
object Test04_List {
def main(args: Array[String]): Unit = {
// 1. 创建一个List
val list1 = List(23, 65, 87)
println(list1)
// 2. 访问和遍历元素
println(list1(1))
// list1(1) = 12
list1.foreach(println)
// 3. 添加元素
val list2 = 10 +: list1
val list3 = list1 :+ 23
println(list1)
println(list2)
println(list3)
println("==================")
val list4 = list2.::(51)
println(list4)
val list5 = Nil.::(13)
println(list5)
val list6 = 73 :: 32 :: Nil
val list7 = 17 :: 28 :: 59 :: 16 :: Nil
println(list7)
// 4. 合并列表
val list8 = list6 :: list7
println(list8)
val list9 = list6 ::: list7
println(list9)
val list10 = list6 ++ list7
println(list10)
}
}
7.5 集合5
package chapter07
import scala.collection.mutable.ListBuffer
object Test05_ListBuffer {
def main(args: Array[String]): Unit = {
// 1. 创建可变列表
val list1: ListBuffer[Int] = new ListBuffer[Int]()
val list2 = ListBuffer(12, 53, 75)
println(list1)
println(list2)
println("==============")
// 2. 添加元素
list1.append(15, 62)
list2.prepend(20)
list1.insert(1, 19, 22)
println(list1)
println(list2)
println("==============")
31 +=: 96 +=: list1 += 25 += 11
println(list1)
println("==============")
// 3. 合并list
val list3 = list1 ++ list2
println(list1)
println(list2)
println("==============")
list1 ++=: list2
println(list1)
println(list2)
println("==============")
// 4. 修改元素
list2(3) = 30
list2.update(0, 89)
println(list2)
// 5. 删除元素
list2.remove(2)
list2 -= 25
println(list2)
}
}
7.6 集合6 数集Set
package chapter07
object Test06_ImmutableSet {
def main(args: Array[String]): Unit = {
// 1. 创建set
val set1 = Set(13, 23, 53, 12, 13, 23, 78)
println(set1)
println("==================")
// 2. 添加元素
val set2 = set1 + 129
println(set1)
println(set2)
println("==================")
// 3. 合并set
val set3 = Set(19, 13, 23, 53, 67, 99)
val set4 = set2 ++ set3
println(set2)
println(set3)
println(set4)
// 4. 删除元素
val set5 = set3 - 13
println(set3)
println(set5)
}
}
7.7 集合7
package chapter07
import scala.collection.mutable
object Test07_MutableSet {
def main(args: Array[String]): Unit = {
// 1. 创建set
val set1: mutable.Set[Int] = mutable.Set(13, 23, 53, 12, 13, 23, 78)
println(set1)
println("==================")
// 2. 添加元素
val set2 = set1 + 11
println(set1)
println(set2)
set1 += 11
println(set1)
val flag1 = set1.add(10)
println(flag1)
println(set1)
val flag2 = set1.add(10)
println(flag2)
println(set1)
println("==================")
// 3. 删除元素
set1 -= 11
println(set1)
val flag3 = set1.remove(10)
println(flag3)
println(set1)
val flag4 = set1.remove(10)
println(flag4)
println(set1)
println("==================")
// 4. 合并两个Set
// val set3 =
val set3 = Set(13, 12, 13, 27, 98)
println(set1)
println(set3)
println("==================")
set1 ++ set3
val set4 = set1 ++ set3
println(set1)
println(set3)
println(set4)
println("==================")
println(set1)
println(set3)
set1 ++= set3
println(set1)
}
}
7.8 集合8 映射(散列表)Map
package chapter07
object Test08_ImmutableMap {
def main(args: Array[String]): Unit = {
// 1. 创建map
val map1: Map[String, Int] = Map("a" -> 13, "b" -> 25, "hello" -> 3)
println(map1)
println(map1.getClass)
println("==========================")
// 2. 遍历元素
map1.foreach(println)
map1.foreach( (kv: (String, Int)) => println(kv) )
println("============================")
// 3. 取map中所有的key 或者 value
for (key <- map1.keys){
println(s"$key ---> ${map1.get(key)}")
}
// 4. 访问某一个key的value
println("a: " + map1.get("a").get)
println("c: " + map1.get("c"))
println("c: " + map1.getOrElse("c", 0))
println(map1("a"))
}
}
7.9 集合9
package chapter07
import scala.collection.mutable
object Test09_MutableMap {
def main(args: Array[String]): Unit = {
// 1. 创建map
val map1: mutable.Map[String, Int] = mutable.Map("a" -> 13, "b" -> 25, "hello" -> 3)
println(map1)
println(map1.getClass)
println("==========================")
// 2. 添加元素
map1.put("c", 5)
map1.put("d", 9)
println(map1)
map1 += (("e", 7))
println(map1)
println("====================")
// 3. 删除元素
println(map1("c"))
map1.remove("c")
println(map1.getOrElse("c", 0))
map1 -= "d"
println(map1)
println("====================")
// 4. 修改元素
map1.update("c", 5)
map1.update("e", 10)
println(map1)
println("====================")
// 5. 合并两个Map
val map2: Map[String, Int] = Map("aaa" -> 11, "b" -> 29, "hello" -> 5)
// map1 ++= map2
println(map1)
println(map2)
println("---------------------------")
val map3: Map[String, Int] = map2 ++ map1
println(map1)
println(map2)
println(map3)
}
}
7.10 集合10 元祖tuple
package chapter07
object Test10_Tuple {
def main(args: Array[String]): Unit = {
// 1. 创建元组
val tuple: (String, Int, Char, Boolean) = ("hello", 100, 'a', true)
println(tuple)
// 2. 访问数据
println(tuple._1)
println(tuple._2)
println(tuple._3)
println(tuple._4)
println(tuple.productElement(1))
println("====================")
// 3. 遍历元组数据
for (elem <- tuple.productIterator)
println(elem)
// 4. 嵌套元组
val mulTuple = (12, 0.3, "hello", (23, "scala"), 29)
println(mulTuple._4._2)
}
}
7.11 集合11 集合的常用函数
package chapter07
object Test11_CommonOp {
def main(args: Array[String]): Unit = {
val list = List(1,3,5,7,2,89)
val set = Set(23,34,423,75)
// (1)获取集合长度
println(list.length)
// (2)获取集合大小
println(set.size)
// (3)循环遍历
for (elem <- list)
println(elem)
set.foreach(println)
// (4)迭代器
for (elem <- list.iterator) println(elem)
println("====================")
// (5)生成字符串
println(list)
println(set)
println(list.mkString("--"))
// (6)是否包含
println(list.contains(23))
println(set.contains(23))
}
}
这个比较实用一点 !!!
7.12 集合12 衍生集合
package chapter07
object Test12_DerivedCollection {
def main(args: Array[String]): Unit = {
val list1 = List(1,3,5,7,2,89)
val list2 = List(3,7,2,45,4,8,19)
// (1)获取集合的头
println(list1.head)
// (2)获取集合的尾(不是头的就是尾)
println(list1.tail)
// (3)集合最后一个数据
println(list2.last)
// (4)集合初始数据(不包含最后一个)
println(list2.init)
// (5)反转
println(list1.reverse)
// (6)取前(后)n个元素
println(list1.take(3))
println(list1.takeRight(4))
// (7)去掉前(后)n个元素
println(list1.drop(3))
println(list1.dropRight(4))
println("=========================")
// (8)并集
val union = list1.union(list2)
println("union: " + union)
println(list1 ::: list2)
// 如果是set做并集,会去重
val set1 = Set(1,3,5,7,2,89)
val set2 = Set(3,7,2,45,4,8,19)
val union2 = set1.union(set2)
println("union2: " + union2)
println(set1 ++ set2)
println("-----------------------")
// (9)交集
val intersection = list1.intersect(list2)
println("intersection: " + intersection)
println("-----------------------")
// (10)差集
val diff1 = list1.diff(list2)
val diff2 = list2.diff(list1)
println("diff1: " + diff1)
println("diff2: " + diff2)
println("-----------------------")
// (11)拉链
println("zip: " + list1.zip(list2))
println("zip: " + list2.zip(list1))
println("-----------------------")
// (12)滑窗
for (elem <- list1.sliding(3))
println(elem)
println("-----------------------")
for (elem <- list2.sliding(4, 2))
println(elem)
println("-----------------------")
for (elem <- list2.sliding(3, 3))
println(elem)
}
}
7.13 集合13 集合计算简单函数(sum求和...)
package chapter07
object Test13_SimpleFunction {
def main(args: Array[String]): Unit = {
val list = List(5,1,8,2,-3,4)
val list2 = List(("a", 5), ("b", 1), ("c", 8), ("d", 2), ("e", -3), ("f", 4))
// (1)求和
var sum = 0
for (elem <- list){
sum += elem
}
println(sum)
println(list.sum)
// (2)求乘积
println(list.product)
// (3)最大值
println(list.max)
println(list2.maxBy( (tuple: (String, Int)) => tuple._2 ))
println(list2.maxBy( _._2 ))
// (4)最小值
println(list.min)
println(list2.minBy(_._2))
println("========================")
// (5)排序
// 5.1 sorted
val sortedList = list.sorted
println(sortedList)
// 从大到小逆序排序
println(list.sorted.reverse)
// 传入隐式参数
println(list.sorted(Ordering[Int].reverse))
println(list2.sorted)
// 5.2 sortBy
println(list2.sortBy(_._2))
println(list2.sortBy(_._2)(Ordering[Int].reverse))
// 5.3 sortWith
println(list.sortWith( (a: Int, b: Int) => {a < b} ))
println(list.sortWith( _ < _ ))
println(list.sortWith( _ > _))
}
}
7.14 集合14 集合计算高级函数(过滤...)
package chapter07
object Test14_HighLevelFunction_Map {
def main(args: Array[String]): Unit = {
val list = List(1,2,3,4,5,6,7,8,9)
// 1. 过滤
// 选取偶数
val evenList = list.filter( (elem: Int) => {elem % 2 == 0} )
println(evenList)
// 选取奇数
println(list.filter( _ % 2 == 1 ))
println("=======================")
// 2. 映射map
// 把集合中每个数乘2
println(list.map(_ * 2))
println(list.map( x => x * x))
println("=======================")
// 3. 扁平化
val nestedList: List[List[Int]] = List(List(1,2,3),List(4,5),List(6,7,8,9))
val flatList = nestedList(0) ::: nestedList(1) ::: nestedList(2)
println(flatList)
val flatList2 = nestedList.flatten
println(flatList2)
println("=======================")
// 4. 扁平映射
// 将一组字符串进行分词,并保存成单词的列表
val strings: List[String] = List("hello world", "hello scala", "hello java", "we study")
val splitList: List[Array[String]] = strings.map( _.split(" ") ) // 分词
val flattenList = splitList.flatten // 打散扁平化
println(flattenList)
val flatmapList = strings.flatMap(_.split(" "))
println(flatmapList)
println("========================")
// 5. 分组groupBy
// 分成奇偶两组
val groupMap: Map[Int, List[Int]] = list.groupBy( _ % 2)
val groupMap2: Map[String, List[Int]] = list.groupBy( data => if (data % 2 == 0) "偶数" else "奇数")
println(groupMap)
println(groupMap2)
// 给定一组词汇,按照单词的首字母进行分组
val wordList = List("china", "america", "alice", "canada", "cary", "bob", "japan")
println( wordList.groupBy( _.charAt(0) ) )
}
}
7.15 集合15 redeuc归约,fold折叠
package chapter07
object Test15_HighLevelFunction_Reduce {
def main(args: Array[String]): Unit = {
val list = List(1,2,3,4)
// 1. reduce
println(list.reduce( _ + _ ))
println(list.reduceLeft(_ + _))
println(list.reduceRight(_ + _))
println("===========================")
val list2 = List(3,4,5,8,10)
println(list2.reduce(_ - _)) // -24
println(list2.reduceLeft(_ - _))
println(list2.reduceRight(_ - _)) // 3 - (4 - (5 - (8 - 10))), 6
println("===========================")
// 2. fold
println(list.fold(10)(_ + _)) // 10 + 1 + 2 + 3 + 4
println(list.foldLeft(10)(_ - _)) // 10 - 1 - 2 - 3 - 4
println(list2.foldRight(11)(_ - _)) // 3 - (4 - (5 - (8 - (10 - 11)))), -5
}
}
7.16 集合16 合并列表(如果有相同的key就把value值相加)
package chapter07
import scala.collection.mutable
object Test16_MergeMap {
def main(args: Array[String]): Unit = {
val map1 = Map("a" -> 1, "b" -> 3, "c" -> 6)
val map2 = mutable.Map("a" -> 6, "b" -> 2, "c" -> 9, "d" -> 3)
// println(map1 ++ map2)
val map3 = map1.foldLeft(map2)(
(mergedMap, kv) => {
val key = kv._1
val value = kv._2
mergedMap(key) = mergedMap.getOrElse(key, 0) + value
mergedMap
}
)
println(map3)
}
}
7.17 集合17
package chapter07
object Test17_CommonWordCount {
def main(args: Array[String]): Unit = {
val stringList: List[String] = List(
"hello",
"hello world",
"hello scala",
"hello spark from scala",
"hello flink from scala"
)
// 1. 对字符串进行切分,得到一个打散所有单词的列表
// val wordList1: List[Array[String]] = stringList.map(_.split(" "))
// val wordList2: List[String] = wordList1.flatten
// println(wordList2)
val wordList = stringList.flatMap(_.split(" "))
println(wordList)
// 2. 相同的单词进行分组
val groupMap: Map[String, List[String]] = wordList.groupBy(word => word)
println(groupMap)
// 3. 对分组之后的list取长度,得到每个单词的个数
val countMap: Map[String, Int] = groupMap.map(kv => (kv._1, kv._2.length))
// 4. 将map转换为list,并排序取前3
val sortList: List[(String, Int)] = countMap.toList
.sortWith( _._2 > _._2 )
.take(3)
println(sortList)
}
}
7.18 集合18
package chapter07
object Test18_ComplexWordCount {
def main(args: Array[String]): Unit = {
val tupleList: List[(String, Int)] = List(
("hello", 1),
("hello world", 2),
("hello scala", 3),
("hello spark from scala", 1),
("hello flink from scala", 2)
)
// 思路一:直接展开为普通版本
val newStringList: List[String] = tupleList.map(
kv => {
(kv._1.trim + " ") * kv._2
}
)
println(newStringList)
// 接下来操作与普通版本完全一致
val wordCountList: List[(String, Int)] = newStringList
.flatMap(_.split(" ")) // 空格分词
.groupBy( word => word ) // 按照单词分组
.map( kv => (kv._1, kv._2.size) ) // 统计出每个单词的个数
.toList
.sortBy(_._2)(Ordering[Int].reverse)
.take(3)
println(wordCountList)
println("================================")
// 思路二:直接基于预统计的结果进行转换
// 1. 将字符串打散为单词,并结合对应的个数包装成二元组
val preCountList: List[(String, Int)] = tupleList.flatMap(
tuple => {
val strings: Array[String] = tuple._1.split(" ")
strings.map( word => (word, tuple._2) )
}
)
println(preCountList)
// 2. 对二元组按照单词进行分组
val preCountMap: Map[String, List[(String, Int)]] = preCountList.groupBy( _._1 )
println(preCountMap)
// 3. 叠加每个单词预统计的个数值
val countMap: Map[String, Int] = preCountMap.mapValues(
tupleList => tupleList.map(_._2).sum
).toMap
println(countMap)
// 4. 转换成list,排序取前3
val countList = countMap.toList
.sortWith(_._2 > _._2)
.take(3)
println(countList)
}
}
7.19 集合19
package chapter07
import scala.collection.immutable.Queue
import scala.collection.mutable
import scala.collection.parallel.immutable
object Test19_Queue {
def main(args: Array[String]): Unit = {
// 创建一个可变队列
val queue: mutable.Queue[String] = new mutable.Queue[String]()
queue.enqueue("a", "b", "c")
println(queue)
println(queue.dequeue())
println(queue)
println(queue.dequeue())
println(queue)
queue.enqueue("d", "e")
println(queue)
println(queue.dequeue())
println(queue)
println("==========================")
// 不可变队列
val queue2: Queue[String] = Queue("a", "b", "c")
val queue3 = queue2.enqueue("d")
println(queue2)
println(queue3)
}
}
7.20 集合20
package chapter07
import scala.collection.immutable
import scala.collection.parallel.immutable.ParSeq
object Test20_Parallel {
def main(args: Array[String]): Unit = {
val result: immutable.IndexedSeq[Long] = (1 to 100).map(
x => Thread.currentThread.getId
)
println(result)
val result2: ParSeq[Long] = (1 to 100).par.map(
x => Thread.currentThread.getId
)
println(result2)
}
}
第 8 章 模式匹配
8.1 模式匹配1
package chapter08
object Test01_PatternMatchBase {
def main(args: Array[String]): Unit = {
// 1. 基本定义语法
val x: Int = 5
val y: String = x match {
case 1 => "one"
case 2 => "two"
case 3 => "three"
case _ => "other"
}
println(y)
// 2. 示例:用模式匹配实现简单二元运算
val a = 25
val b = 13
def matchDualOp(op: Char): Int = op match {
case '+' => a + b
case '-' => a - b
case '*' => a * b
case '/' => a / b
case '%' => a % b
case _ => -1
}
println(matchDualOp('+'))
println(matchDualOp('/'))
println(matchDualOp('\\'))
println("=========================")
// 3. 模式守卫
// 求一个整数的绝对值
def abs(num: Int): Int = {
num match {
case i if i >= 0 => i
case i if i < 0 => -i
}
}
println(abs(67))
println(abs(0))
println(abs(-24))
}
}
8.2 模式匹配2
package chapter08
object Test02_MatchTypes {
def main(args: Array[String]): Unit = {
// 1. 匹配常量
def describeConst(x: Any): String = x match {
case 1 => "Int one"
case "hello" => "String hello"
case true => "Boolean true"
case '+' => "Char +"
case _ => ""
}
println(describeConst("hello"))
println(describeConst('+'))
println(describeConst(0.3))
println("==================================")
// 2. 匹配类型
def describeType(x: Any): String = x match {
case i: Int => "Int " + i
case s: String => "String " + s
case list: List[String] => "List " + list
case array: Array[Int] => "Array[Int] " + array.mkString(",")
case a => "Something else: " + a
}
println(describeType(35))
println(describeType("hello"))
println(describeType(List("hi", "hello")))
println(describeType(List(2, 23)))
println(describeType(Array("hi", "hello")))
println(describeType(Array(2, 23)))
// 3. 匹配数组
for (arr <- List(
Array(0),
Array(1, 0),
Array(0, 1, 0),
Array(1, 1, 0),
Array(2, 3, 7, 15),
Array("hello", 1, 30),
)) {
val result = arr match {
case Array(0) => "0"
case Array(1, 0) => "Array(1, 0)"
case Array(x, y) => "Array: " + x + ", " + y // 匹配两元素数组
case Array(0, _*) => "以0开头的数组"
case Array(x, 1, z) => "中间为1的三元素数组"
case _ => "something else"
}
println(result)
}
println("=========================")
// 4. 匹配列表
// 方式一
for (list <- List(
List(0),
List(1, 0),
List(0, 0, 0),
List(1, 1, 0),
List(88),
List("hello")
)) {
val result = list match {
case List(0) => "0"
case List(x, y) => "List(x, y): " + x + ", " + y
case List(0, _*) => "List(0, ...)"
case List(a) => "List(a): " + a
case _ => "something else"
}
println(result)
}
// 方式二
val list1 = List(1, 2, 5, 7, 24)
val list = List(24)
list match {
case first :: second :: rest => println(s"first: $first, second: $second, rest: $rest")
case _ => println("something else")
}
println("===========================")
// 5. 匹配元组
for (tuple <- List(
(0, 1),
(0, 0),
(0, 1, 0),
(0, 1, 1),
(1, 23, 56),
("hello", true, 0.5)
)){
val result = tuple match {
case (a, b) => "" + a + ", " + b
case (0, _) => "(0, _)"
case (a, 1, _) => "(a, 1, _) " + a
case (x, y, z) => "(x, y, z) " + x + " " + y + " " + z
case _ => "something else"
}
println(result)
}
}
}
8.3 模式匹配3
package chapter08
object Test03_MatchTupleExtend {
def main(args: Array[String]): Unit = {
// 1. 在变量声明时匹配
val (x, y) = (10, "hello")
println(s"x: $x, y: $y")
val List(first, second, _*) = List(23, 15, 9, 78)
println(s"first: $first, second: $second")
val fir :: sec :: rest = List(23, 15 , 9, 78)
println(s"first: $fir, second: $sec, rest: $rest")
println("=====================")
// 2. for推导式中进行模式匹配
val list: List[(String, Int)] = List(("a", 12), ("b", 35), ("c", 27), ("a", 13))
// 2.1 原本的遍历方式
for (elem <- list){
println(elem._1 + " " + elem._2)
}
// 2.2 将List的元素直接定义为元组,对变量赋值
for ((word, count) <- list ){
println(word + ": " + count)
}
println("-----------------------")
// 2.3 可以不考虑某个位置的变量,只遍历key或者value
for ((word, _) <- list)
println(word)
println("-----------------------")
// 2.4 可以指定某个位置的值必须是多少
for (("a", count) <- list){
println(count)
}
}
}
8.4 模式匹配4
package chapter08
object Test04_MatchObject {
def main(args: Array[String]): Unit = {
val student = new Student("alice", 19)
// 针对对象实例的内容进行匹配
val result = student match {
case Student("alice", 18) => "Alice, 18"
case _ => "Else"
}
println(result)
}
}
// 定义类
class Student(val name: String, val age: Int)
// 定义伴生对象
object Student {
def apply(name: String, age: Int): Student = new Student(name, age)
// 必须实现一个unapply方法,用来对对象属性进行拆解
def unapply(student: Student): Option[(String, Int)] = {
if (student == null){
None
} else {
Some((student.name, student.age))
}
}
}
8.5 模式匹配5
package chapter08
object Test05_MatchCaseClass {
def main(args: Array[String]): Unit = {
val student = Student1("alice", 18)
// 针对对象实例的内容进行匹配
val result = student match {
case Student1("alice", 18) => "Alice, 18"
case _ => "Else"
}
println(result)
}
}
// 定义样例类
case class Student1(name: String, age: Int)
8.6 模式匹配6
package chapter08
object Test06_PartialFunction {
def main(args: Array[String]): Unit = {
val list: List[(String, Int)] = List(("a", 12), ("b", 35), ("c", 27), ("a", 13))
// 1. map转换,实现key不变,value2倍
val newList = list.map( tuple => (tuple._1, tuple._2 * 2) )
// 2. 用模式匹配对元组元素赋值,实现功能
val newList2 = list.map(
tuple => {
tuple match {
case (word, count) => (word, count * 2)
}
}
)
// 3. 省略lambda表达式的写法,进行简化
val newList3 = list.map {
case (word, count) => (word, count * 2)
}
println(newList)
println(newList2)
println(newList3)
// 偏函数的应用,求绝对值
// 对输入数据分为不同的情形:正、负、0
val positiveAbs: PartialFunction[Int, Int] = {
case x if x > 0 => x
}
val negativeAbs: PartialFunction[Int, Int] = {
case x if x < 0 => -x
}
val zeroAbs: PartialFunction[Int, Int] = {
case 0 => 0
}
def abs(x: Int): Int = (positiveAbs orElse negativeAbs orElse zeroAbs) (x)
println(abs(-67))
println(abs(35))
println(abs(0))
}
}
第 9 章 异常与泛型
9.1 异常
package chapter09plus
object Test01_Exception {
def main(args: Array[String]): Unit = {
try{
val n = 10 / 0
} catch {
case e: ArithmeticException => {
println("发生算术异常")
}
case e: Exception => {
println("发生一般异常")
}
} finally {
println("处理结束")
}
}
}
9.2 泛型 1
package chapter09plus
object Test02_Implicit {
def main(args: Array[String]): Unit = {
val new12 = new MyRichInt(12)
println(new12.myMax(15))
// 1. 隐式函数
implicit def convert(num: Int): MyRichInt = new MyRichInt(num)
println(12.myMax(15))
println("============================")
// 2. 隐式类
implicit class MyRichInt2(val self: Int) {
// 自定义比较大小的方法
def myMax2(n: Int): Int = if ( n < self ) self else n
def myMin2(n: Int): Int = if ( n < self ) n else self
}
println(12.myMin2(15))
println("============================")
// 3. 隐式参数
implicit val str: String = "alice"
// implicit val str2: String = "alice2"
implicit val num: Int = 18
def sayHello()(implicit name: String): Unit = {
println("hello, " + name)
}
def sayHi(implicit name: String = "atguigu"): Unit = {
println("hi, " + name)
}
sayHello
sayHi
// 简便写法
def hiAge(): Unit = {
println("hi, " + implicitly[Int])
}
hiAge()
}
}
// 自定义类
class MyRichInt(val self: Int) {
// 自定义比较大小的方法
def myMax(n: Int): Int = if ( n < self ) self else n
def myMin(n: Int): Int = if ( n < self ) n else self
}
9.3 泛型 2
package chapter09plus
object Test03_Generics {
def main(args: Array[String]): Unit = {
// 1. 协变和逆变
val child: Parent = new Child
// val childList: MyCollection[Parent] = new MyCollection[Child]
val childList: MyCollection[SubChild] = new MyCollection[Child]
// 2. 上下限
def test[A <: Child](a: A): Unit = {
println(a.getClass.getName)
}
test[SubChild](new SubChild)
}
}
// 定义继承关系
class Parent {}
class Child extends Parent {}
class SubChild extends Child {}
// 定义带泛型的集合类型
class MyCollection[-E] {}