package com.yl.Scala
object ListTest {
def main(args : Array[String]){
//List连接案例,符号“:::”完成
val cList = List(1,2,3,4) ::: List(5,6) ::: List(7,8)
println(cList)
println(cList.length) //求长度
//字符串List[String]常用操作
val bigData = List("Hadoop", "Spark", "Others")
println(bigData.last) //Others
println(bigData.init) //除了最后一个元素,其余元素合为一个列表 List(Hadoop, Spark)
println(bigData.reverse) //逆序返回 List(Others, Spark, Hadoop)
println(bigData) //List(Hadoop, Spark, Others)
println(bigData take 2) //取前两个元素 List(Hadoop, Spark)
println(bigData drop 2) //舍去前两个元素 List(Others)
println(bigData splitAt 2)//合为包含两个列表的列表,前2个元素为一个列表 (List(Hadoop, Spark),List(Others))
println(bigData apply 2) //下标为2的元素 Others
println(bigData(2)) //下标为2的元素 Others
println
//Char类型字符List[Char]常用操作
val data = List('a', 'b', 'c', 'd', 'e', 'f')
println(data.indices) //打印输出下标编号 Range(0, 1, 2, 3, 4, 5)
println(data.indices zip data) //配对 Vector((0,a), (1,b), (2,c), (3,d), (4,e), (5,f))
println(data.zipWithIndex) // List((a,0), (b,1), (c,2), (d,3), (e,4), (f,5))
println(data.toString) // List(a, b, c, d, e, f)
println(data.mkString("[", ",", "]"))//[a,b,c,d,e,f]
println(data.mkString("*")) // a*b*c*d*e*f
println(data.mkString) // abcdef
//List的一些应用
println
println("List的一些应用:")
println("data = " + data)
//生成指定类型字符串
val buffer = new StringBuilder
data addString(buffer, "<>")
println("buffer = " + buffer) //buffer = a<>b<>c<>d<>e<>f
//和数组相互转换
val arr = data.toArray
print("arr的元素:")
arr.foreach(print) //打印出数组元素 abcdef
println
println("lst = " + arr.toList) //lst = List(a, b, c, d, e, f)
//copytoArray方法的使用
val arr2 = new Array[Char](10)
data.copyToArray(arr2, 3) //从第四个位置开始将data的元素复制到arr2中
arr2.foreach(print) // ---abcdef- "-"代表空格
println
//迭代器
val iter = data.toIterator
print(iter.next) //a
print(iter.next) //b
print(iter.next) //c
}
}
运行结果:
List(1, 2, 3, 4, 5, 6, 7, 8)
8
Others
List(Hadoop, Spark)
List(Others, Spark, Hadoop)
List(Hadoop, Spark, Others)
List(Hadoop, Spark)
List(Others)
(List(Hadoop, Spark),List(Others))
Others
Others
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
List的一些应用:
data = List(a, b, c, d, e, f)
buffer = a<>b<>c<>d<>e<>f
arr的元素:abcdef
lst = List(a, b, c, d, e, f)