1. 程式人生 > >快學scala之List操作

快學scala之List操作

object list_opt {

  def main(args: Array[String]) {
    // init list
val list1 = List("a", "b", "c")
    val list2 = List(1, 2, 3)
    val list3 = "a" :: "b" :: "c" :: Nil // last element is Nil
    // ::: connect two list
val list_1_2 = list1 ::: list2
println(list_1_2) //List(a, b, c, 1, 2, 3)
val list_2 
= 0 :: list2 // add to head // get element list(index),start with 0 println(list1(1)) // b // get head println("head : " + list1.head + " tail :" + list1.tail) //head : a tail :List(b, c) println("second element : " + list1.tail.head) //second element : b // basic opt val l = List("hello", "scala", "java"
, "hadoop") println(l.count(s => s.length == 5)) // 2 count the element length equal 5 l.filter(s => s.length == 5).foreach(println) //hello scala list2.map(_ + 1).foreach(println) // 2 3 4 println(list2.sum) // 6 println(list_1_2.exists(s => s == "c")) //true l.mkString(",").foreach(println) l
.sortBy(s => s.toLowerCase()).foreach(println) // match element val temp = List("scala", "java", "hadoop") val List(a, b, c) = temp println("a : " + a + " b: " + b + " c : " + c) println(temp.tail) //List(java, hadoop) // this method is anonymous method val x :: rest = temp print("x : " + x + " rest : " + rest) //x : scala rest : List(java, hadoop)List(scala, java) /* method : l.head :get first element l.init :return element expect last one l.isEmpty : l.last : return last element l.map(s => s + ",") l.mkString(",") l.remove(s => s.length == 4) l.reverse : reverse element l.sort() : sort l.tail : return list expect first element */ // take first 2 element println(temp take 2) // expect last element println(temp init) // drop first element println(temp drop 1) // splitAt index:split into to list by index println(temp splitAt 2) // get element by index println(temp apply (2)) val data = List('a', 'b', 'c', 'd', 'e') // print index println(data indices) //Range(0, 1, 2, 3, 4) // zip println(data.indices zip data) //Vector((0,a), (1,b), (2,c), (3,d), (4,e)) //convert into new list println(data.toString()) // List(a, b, c, d, e) println(data mkString("[", ",", "]")) //[a,b,c,d,e] println(data mkString " ") //a b c d e // iterator element val it = data.iterator // val it = data.toIterator // for (i <- it) // println(i) while (it.hasNext) println(it.next()) val li = List(1, 2, 3, 4, 5) println(li partition (_ > 3)) //(List(4, 5),List(1, 2, 3)) } // sort list val shuffledList = List(4, 3, 8, 9, 1, 6, 2) sort(shuffledList).foreach(println) def sort(list: List[Int]): List[Int] = list match { case List() => List() case head :: tail => compute(head, sort(tail)) } def compute(data: Int, dataSet: List[Int]): List[Int] = dataSet match { case List() => List(data) case head :: tail => if (data <= head) data :: dataSet else head :: compute(data, tail) } }