[learning scala] collections

object SparkTest005 {
  def main(args: Array[String]): Unit = {
    /**
      * Chapter 5 functions
      */

    def jump(title: String = ""): Unit = print(s"\n ---------${title}----------- \n")

    val nums = List(1, 3, 4, 5)
    println(nums.head)
    print(nums.tail) // the remaining list except head

    jump("collections with high-order functions")

    val colors = List("red", "blue", "yellow")

    colors.foreach((c: String) => print(s"$c\t\t"))
    println()
    colors.foreach(c => println(c))

    println()
    val newColors = colors.map((c: String) => s"*$c")
    newColors.foreach(c => println(c))

    println()
    val nums1 = List(1, 2, 3, 4)
    val nums1_1 = nums1.map(_ + 100)
    nums1_1.foreach(x => print(x.toString + "@@@"))

    println()
    val res = colors.reduce((c1: String, c2: String) => c1 + ‘-‘ + c2)
    println(res)

    val max = colors.reduce((c1: String, c2: String) => if (c1.size > c2.size) c1 else c2)
    println(s"longest string is: $max")

    val uniq = Set(10, 10, 10, 20, 30, 30)
    uniq.foreach(c => print(s"$c\t"))
    val sum = uniq.reduce((c1, c2) => c1 + c2)
    val sum2 = uniq.reduce(_ + _)
    print(s"\nsum2 is: $sum2\n")

    val colorMap = Map("red" -> 1, "blue" -> 2, "yellow" -> 3)
    colorMap.foreach(c => println(c._1, c._2))
    val (maxColorKey, maxColorValue) = colorMap.reduce((c1: (String, Int), c2: (String, Int)) => if (c1._2 > c2._2) c1 else c2)
    println(maxColorValue)

    val isContainWhite = colorMap.contains("white")
    println(isContainWhite)

    var copyColors = colors
    while (!copyColors.isEmpty) {
      print(copyColors.head + ‘*‘)
      copyColors = copyColors.tail
    }

    println()
    copyColors = colors
    while(copyColors != Nil) {
      print(copyColors.head + ‘&‘)
      copyColors = copyColors.tail
    }

    @annotation.tailrec
    def visit(i: List[String]): Unit = {if (i.size > 0) {print(i.head + ‘?‘); visit(i.tail)}} // functions without changing anything
    println()
    visit(colors)

    val emptyList: List[Int] = List()
    val singleEntryList: List[Int] = List(100)

    if (emptyList == Nil) print("\nyes") else print("no")
    if (singleEntryList.tail == Nil) print("\nyes\n") else print("no")

    val createList = 1 :: 2 :: 3 :: Nil // missing Nil will lead to an error

    var copyColors2 = createList
    while(copyColors2 != Nil) {
      print(s"${copyColors2.head}&")
      copyColors2 = copyColors2.tail
    }

    val first = 1 :: Nil
    val second = 2 :: first // prepend
    val third = first ::: second // prepend list with another list

    jump()
    third.foreach(i => println(i))

    val fourth = List(1, 2) ++ Set(3, 3, 4)
    jump()
    fourth.foreach(i => println(i))

    val chars = List(1, 2, 3, 4)
    val chars2 = chars drop 2
    jump()
    chars2.foreach(i => println(i))

    val chars3 = chars.filter(x => x > 2)
    val chars3_1 = chars.filter(_ > 2)
    jump()
    chars3_1.foreach(x => print(x.toString + ‘,‘))

    jump()
    val chars4 = chars.slice(1, chars.size)
    chars4.foreach(x => print(x.toString + ‘,‘))

    // take, drop, slice, zip, sorted, sortedBy, splitAt, reverse, partition, flatten, distinct...
    val par = List(100, 2, 3, 4) partition (_ < 3)
    jump()
    par._1.foreach(x => print(x.toString + ‘,‘))
    println()
    par._2.foreach(x => print(x.toString + ‘,‘))

    val greeter = List("hello,world,!")
    val greeter1 = greeter.flatMap(_.split(‘,‘))
    jump()
    greeter1.foreach(x => print(x.toString + ‘~‘))

    jump("reduce")

    val n1 = List(1, 2, 3, 4, 10)
    val m = n1.reduce((x, y) => if(x > y) x else y)
    val m2 = n1.max
    val m3 = n1.contains(3)
    println(s"m is: ${m3}")

    jump("a reduce template")
    def reduceOp[A, B](l: List[A], start: B)(f: (B, A) => B): B = {
      var a = start
      for (i <- l) a = f(a, i)
      a
    }

    //contains 100
    val c = reduceOp(List(1, 2, 100), false) {
      (a, i) => if (a) a else (i == 100)
    }

    // sum
    val s = reduceOp(List(1, 2, 100), 0.0)(_ + _)

    // max
    val mmm = reduceOp(List(1, 2, 100), 0) {
      (a, i) => if (a > i) a else i
    }

    print(c.toString + ",,," + s.toString + ",,," + mmm.toString)

    jump("fold")
    val ss = List(1, 2, 100).fold(0)(_ + _)
    println(ss.toString + "....ss ....")
    val mm = List(1, 2, 100).fold(-0xffffff)((a, b) => if (a > b) a else b)
    println(mm.toString + "...mm...")
    val ssleft = List(1, 2, 100).foldLeft(0)(_ + _)
    println(ssleft.toString + "....ssleft....")

    val scanval = List(1, 2, 100).scan(0)(_ + _)
    val v1 = List(1, 2, 100).scanRight(0)(_ + _)
    val v2 = List(1, 2, 100).scan(-1)((x, y) => if (x > y) x else y)
    val foldSimulate = List(1, 2, 100).scanRight(-1)((x, y) => if (x > y) x else y).head // bad : from right to left
    println(v2)
    println(foldSimulate)

    jump("coverting collections")

    val s1: String = List(1, 2, 3).mkString(",")
    println(List("a", "b", "c").mkString("#"))
    println(List("a", "b", "c").toString + "      !!!")
    println(Map(1 -> "a", 2 -> "b").mkString("?"))
    println(Map(1 -> "a", 2 -> "b").toString + "     !!!!")
    println(s1)

    println(Map(1 -> "a", 2 -> "b").toList)

    val bf = List("a", "b").toBuffer // mutable collection
    bf(0) = "c"
    println(bf(0))

    // extract key from a map put into a list
    val m5 = Map(1 -> "hello", 2 -> "world", 3 ->"scala")
    val l3 = m5.map(_._1)
    val l3_1 = m5.map(x => x._1)
    val l4 = m5.map(_._2)
    println(l3_1)

  }
}

  

时间: 2024-08-07 15:27:03

[learning scala] collections的相关文章

Beginning Scala study note(6) Scala Collections

Scala's object-oriented collections support mutable and immutable type hierarchies. Also support functional higher-order operations such as map, filter, and reduce that let you use expression-oriented programming in collections. Higher-order operatio

learning scala control statement

1 .if satement 与其它语言不同的是,scala if statement 返回的是一个值 scala> val a = if ( 6 > 0 ) 1 else -1a: Int = 1 2. while statement 3. do.. while statement 4 for statement for ( 变量 <-  表达式 ) { 语句块}: scala> for ( i <- 1 to 3 ) println(i)123 scala> for

learning scala read from file

scala读文件:   example: scala> import scala.io.Sourceimport scala.io.Source scala> var inputFile = Source.fromFile("text.txt")inputFile: scala.io.BufferedSource = non-empty iterator scala> for ( line <- inputFile.getLines()) println(lin

learning scala pattern matching 03

code: package com.aura.scala.day01 object patternMatching03 { //当不同类型对象需要调用不同方法时,仅匹配类型的模式非常有用. def goIDLE(device : Device) = device match { case p: Phone => p.screenOff case c:Computer => c.screenSaverOn } } abstract class Device case class Phone(mo

learning scala for comprehensions

code: package com.aura.scala.day01 object forComprehensions { def main(args: Array[String]): Unit = { val userBase = List(User("pan1", 29), User("pan2", 30), User("pan3", 23), User("pan5", 32)) val twentySomethins =

[Learning Scala] Functions

object SparkTest004 { def main(args: Array[String]): Unit = { /** * Chapter 5 functions */ def jump(title: String = ""): Unit = print(s"\n ---------${title}----------- \n") jump("Function Types and Values") def doubleNumbers

learning scala dependency injection

println("Step 1: Create a trait which knows how to do create, read, update and delete operations CRUD to a given database") trait DonutDatabase[A] { def addOrUpdate(donut: A): Long def query(donut: A): A def delete(donut: A): Boolean } println(&

scala简单介绍

前言 Scala 是一门多范式(multi-paradigm)的编程语言,设计初衷是要集成面向对象编程和函数式编程的各种特性. Scala 运行在Java虚拟机上,并兼容现有的Java程序. Scala 源代码被编译成Java字节码,所以它可以运行于JVM之上,并可以调用现有的Java类库. Scala跟JAVA很像,假如你之前已经掌握了JAVA,那么学习Scala将会简单很多 简介 Scala 是 Scalable Language 的简写,是一门多范式的编程语言 联邦理工学院洛桑(EPFL)

How Scala killed the Strategy Pattern

How Scala killed the Strategy Pattern By Alvin Alexander. Last updated: Mar 23, 2014 table of contents [hide] The OOP Strategy Pattern Two immediate thoughts How Scala killed the Strategy Pattern Understanding the 'execute' method Dude, you used 'met