scala入门初级代码训练-31List的一阶函数的使用

原创文章,转载请注明出处!

原文地址: http://www.ptbird.cn/2016/07/19/scala-chuji-demo-31/

There I am,in the world more exciting!

by postbird

www.ptbird.cn



package com.ptbird.scala

/**
* Created by postbird on 2016/5/26.
*
* List 一街函数
*
*/
object ListTest2 {
def main(args: Array[String]): Unit = {

val l1 = List(1, 2, 3, 4)
val l2 = List(5, 6, 7)
val l3 = List(8, 9)

println(l1 ::: l2 ::: l3)
println(l1.length)
// List(1, 2, 3, 4, 5, 6, 7, 8, 9)
// 4

val bigData = List("Hadoop", "Spark", "Scala")
// List本身不能改变,即使reverse之后,也不改变
// length 很慢,应当使用 isEmpty判断是否为空
println(bigData)
println(bigData.last)
println(bigData.init)
println(bigData.reverse)
println(bigData take 2) //打印前两个
println(bigData drop 2) //扔掉前两个
println(bigData splitAt 2) //把前两个分成一个list,之后分成一个list
println(bigData apply 2)
println(bigData(2))
// List(Hadoop, Spark, Scala)
// Scala
// List(Hadoop, Spark)
// List(Scala, Spark, Hadoop)
// List(Hadoop, Spark)
// List(Scala)
// (List(Hadoop, Spark),List(Scala))
// Scala
// Scala

val data = List('a', 'b', 'c', 'd', 'e', 'f')
println(data.indices)
println(data.indices zip data) //进行拉链操作
println(data.zipWithIndex)
println(data.toString)
println(data.mkString("[", ",", "]")) //开始 中间分隔符 结束
println(data.mkString(" "))
println(data.mkString)
// Range(0, 1, 2, 3, 4, 5)
// Vector((0,a), (1,b), (2,c), (3,d), (4,e), (5,f))
// List((a,0), (b,1), (c,2), (d,3), (e,4), (f,5))
// List(a, b, c, d, e, f)
// [a,b,c,d,e,f]
// a b c d e f
// abcdef

val buffer = new StringBuilder
data addString(buffer, "(", ",", ")")
println(buffer)
println(data)
// (a,b,c,d,e,f)
// List(a, b, c, d, e, f)

val arr = data.toArray
println(arr.toList)
// List(a, b, c, d, e, f)

val newArr = new Array[Char](10)
data.copyToArray(newArr, 3)
newArr.foreach(print)
//abcdef

val iterator = data.toIterator
println(iterator.next)
// a
}
}

欢迎评论。
lingkb » scala入门初级代码训练-31List的一阶函数的使用

发表评论