Scala编程

Scala编程详解14:函数式编程之集合操作

2020-05-26  本文已影响0人  勇于自信

大纲
1、Scala的集合体系结构
2、List
3、LinkedList
4、Set
5、集合的函数式编程
6、函数式编程综合案例:统计多个文本内的单词总数

1、Scala的集合体系结构
2、List

object scala_demo09 {
  def main(args: Array[String]): Unit = {
    val list = List(1, 2, 3, 4)
    decorator(list,"jpg")
  }


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


}

打印:

jpg1
jpg2
jpg3
jpg4
3、LinkedList

object scala_demo09 {
  def main(args: Array[String]): Unit = {
    val list = scala.collection.mutable.LinkedList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
    var currentList = list
    var first = true
    while (currentList != Nil && currentList.next != Nil) {
      if (first) {
        currentList.elem = currentList.elem * 2;
        println(currentList.elem)
        first = false
      }
      currentList = currentList.next.next
      if (currentList != Nil) {
        currentList.elem = currentList.elem * 2
        println(currentList.elem)
      }
    }

  }
}

打印:

2
6
10
14
18
4、Set
5、集合的函数式编程
6、函数式编程综合案例:统计多个文本内的单词总数
val lines01 = scala.io.Source.fromFile("C://Users//Administrator//Desktop//test01.txt").mkString
val lines02 = scala.io.Source.fromFile("C://Users//Administrator//Desktop//test02.txt").mkString
val lines = List(lines01, lines02)
lines.flatMap(_.split(" ")).map((_, 1)).map(_._2).reduceLeft(_ + _)
上一篇 下一篇

猜你喜欢

热点阅读