Scala学习第九节:List 以及常规用法

2017-04-06  本文已影响0人  牛马风情

List 的值不能被改变

生成List

scala> var f=List("a","b","c")
f: List[String] = List(a, b, c)

scala> var n=List(1,2,3)
n: List[Int] = List(1, 2, 3)

遍历

scala> for(i<-n){println(i)}
1
2
3

使用:: Nil 构造List

scala> var num=1::2::3::4::Nil
num: List[Int] = List(1, 2, 3, 4)

scala> var num=1::(2::(3::(4::Nil)))
num: List[Int] = List(1, 2, 3, 4)

List 操作

//判断为空
scala> n.isEmpty
res14: Boolean = false

//得到头
scala> n.head
res15: Int = 1
//的到尾
scala> n.last
res19: Int = 3
//得到去掉头的List
scala> n.tail
res16: List[Int] = List(2, 3)
//得到去掉尾的List
scala> n.init
res17: List[Int] = List(1, 2)
//拼接
scala> List(1,2,3):::List(4,5,6)
res18: List[Int] = List(1, 2, 3, 4, 5, 6)
//倒叙
scala> n.reverse
res20: List[Int] = List(3, 2, 1)
//去掉前面n个
scala> n drop 1
res21: List[Int] = List(2, 3)
//得到前面n个
scala> f take 2
res22: List[String] = List(a, b)
// toArray
scala> f.toArray
res25: Array[String] = Array(a, b, c)

其他方法

//apply方法
scala>  List.apply(1, 2, 3)
res139: List[Int] = List(1, 2, 3)

//range方法,构建某一值范围内的List
scala>  List.range(2, 6)
res140: List[Int] = List(2, 3, 4, 5)

//步长为2
scala>  List.range(2, 6,2)
res141: List[Int] = List(2, 4)

//步长为-1
scala>  List.range(2, 6,-1)
res142: List[Int] = List()

scala>  List.range(6,2 ,-1)
res143: List[Int] = List(6, 5, 4, 3)

//构建相同元素的List
scala> List.make(5, "hey")
res144: List[String] = List(hey, hey, hey, hey, hey)
上一篇下一篇

猜你喜欢

热点阅读