集合计算高级函数

发布于:2025-04-11 ⋅ 阅读:(36) ⋅ 点赞:(0)

集合计算高级函数

- 过滤:  

  scala

  val list = List(1, 2, 3, 4, 5)

  println(list.filter(x => x % 2 == 0)) // 输出: List(2, 4)

  

- 映射(map):  

  scala

  println(list.map(x => x + 1)) // 输出: List(2, 3, 4, 5, 6)

  

- 扁平化(flatten):  

  scala

  val nestedList = List(List(1, 2), List(3, 4))

  println(nestedList.flatten) // 输出: List(1, 2, 3, 4)

  

- 扁平化+映射(flatMap):  

  scala

  val words = List("hello world", "hello scala")

  println(words.flatMap(_.split(" "))) // 输出: List(hello, world, hello, scala)

  

- 分组(groupBy):  

  scala

  println(list.groupBy(x => x % 2)) // 输出: Map(1 -> List(1, 3, 5), 0 -> List(2, 4))

  

- 简化(reduce):  

  scala

  println(list.reduce((x, y) => x + y)) // 输出: 15

  

- 折叠(fold):  

  scala

  println(list.fold(0)((x, y) => x + y)) // 输出: 15

  

 

 7.7.5 复杂WordCount案例

scala

val lines = List("hello scala", "hello world", "hello spark")

val wordCount = lines

  .flatMap(_.split(" "))

  .groupBy(word => word)

  .map(kv => (kv._1, kv._2.size))

  .toList

  .sortBy(-_._2)

println(wordCount) // 输出: List((hello,3), (scala,1), (world,1), (spark,1))

 

 

 7.8 队列

scala

import scala.collection.mutable.Queue

val queue = Queue(1, 2, 3)

queue.enqueue(4) // 入队

println(queue.dequeue()) // 出队,输出: 1

 

 

 7.9 并行集合

scala

val list = (1 to 100).toList

val parList = list.par // 转换为并行集合

println(parList.map(_ 2)) // 并行计算

 

 

 第8章 模式匹配

- 匹配常量:  

  scala

  val x: Any = 5

  x match {

    case 5 => println("Int five")

    case "hello" => println("String hello")

    case _ => println("unknown")

  }

  

- 匹配类型:  

  scala

  def describe(x: Any) = x match {

    case i: Int => "Int"

    case s: String => "String"

    case _ => "unknown"

  }

  println(describe(5)) // 输出: Int

  

- 匹配列表:  

  scala

  List(1, 2, 3) match {

    case x :: y :: rest => println(s"first=$x, second=$y, rest=$rest")

    case _ => println("other")

  }

  

 

 第9章 异常

scala

try {

  val n = 10 / 0

} catch {

  case e: ArithmeticException => println("Arithmetic exception")

  case e: Exception => prin