1. 程式人生 > >Scala入門二——入門練習

Scala入門二——入門練習

入門練習題

package com.ghq.scala

/**
  * @author ${user}
  */
object Hw {

  def main(args: Array[String]): Unit = {
    //建立一個List
    val lst0 = List(1,7,9,8,0,3,5,4,6,2)
    //將lst0中每個元素乘以10後生成一個新的集合
    val ls2 = lst0.map(_*10)
    println(ls2)//List(10, 70, 90, 80, 0, 30, 50, 40, 60, 20)
    //將lst0中的偶數取出來生成一個新的集合
    val ls3 = lst0.filter(_%2
==0) println(ls3)//List(8, 0, 4, 6, 2) //將lst0排序後生成一個新的集合 val ls4 = lst0.sortWith(_>_) println(ls4)//List(9, 8, 7, 6, 5, 4, 3, 2, 1, 0) val ls5 = lst0.sortWith(_<_) println(ls5)//List(0, 1, 2, 3, 4, 5, 6, 7, 8, 9) val ls6 = lst0.sorted println(ls6)//List(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
val aa = List("banana", "pear", "apple", "orange").sortWith(_.length < _.length) println(aa)//List(pear, apple, banana, orange) //反轉順序 val res1 = lst0.reverse println(res1)//List(2, 6, 4, 5, 3, 0, 8, 9, 7, 1) //將lst0中的元素4個一組,型別為Iterator[List[Int]] val grouped = lst0.grouped(4) println(grouped)//non-empty iterator
//將Iterator轉換成List println(grouped.toBuffer)//ArrayBuffer(List(1, 7, 9, 8), List(0, 3, 5, 4), List(6, 2)) //將多個list壓扁成一個List val a = List(List(1, 7, 9, 8), List(0, 3, 5, 4), List(6, 2)) println(a.flatten)//List(1, 7, 9, 8, 0, 3, 5, 4, 6, 2) val list01 = List(5,6,4,7) val list02 = List(1,2,3,4) //求並集 val union = (list01 ++ list02).toSet println(union)//Set(5, 1, 6, 2, 7, 3, 4) //求交集 val inter = list01.toSet intersect list02.toSet println(inter.toBuffer)//ArrayBuffer(4) //求差集 val sub01 = union -- inter println(sub01)//Set(5, 1, 6, 2, 7, 3) val sub02 = union diff inter println(sub02)//Set(5, 1, 6, 2, 7, 3) } }