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

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)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • importUIKit classViewController:UITabBarController{ enumD...
    明哥_Young阅读 3,922评论 1 10
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,032评论 19 139
  • 常量与变量使用let来声明常量,使用var来声明变量。声明的同时赋值的话,编译器会自动推断类型。值永远不会被隐式转...
    莫_名阅读 467评论 0 1
  • 胡乱的不知道在说什么,想说的永远也说不出口,憋在心里,成为了一个永恒,然后……不,没有然后。 毕业季一个个的来临,...
    瘗心阅读 340评论 0 0
  • 这是四十年前的事了。 洼里的庄稼,再晚也不过秋分己收完了,最晚在寒露之前该种的小麦也种上了。地净场光。生产队的农活...
    墨云轩阅读 686评论 0 0