当前位置: 移动技术网 > IT编程>开发语言>Java > Scala常用List列表操作方法示例

Scala常用List列表操作方法示例

2019年07月19日  | 移动技术网IT编程  | 我要评论

把scala list的几种常见方法梳理汇总如下,日常开发场景基本上够用了。

创建列表

scala> val days = list("sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday")
days: list[string] = list(sunday, monday, tuesday, wednesday, thursday, friday, saturday)

创建空列表

scala> val l = nil
l: scala.collection.immutable.nil.type = list()
 
scala> val l = list()
l: list[nothing] = list()

用字符串创建列表

scala> val l = "hello" :: "hi" :: "hah" :: "wow" :: "woow" :: nil
l: list[string] = list(hello, hi, hah, wow, woow)

用“:::”叠加创建新列表

scala> val wow = l ::: list("wooow", "woooow")
wow: list[string] = list(hello, hi, hah, wow, woow, wooow, woooow)

通过索引获取列表值

scala> l(3)
res0: string = wow

获取值长度为3的元素数目

scala> l.count(s => s.length == 3)
res1: int = 2

返回去掉l头两个元素的新列表

scala> l.drop(2)
res2: list[string] = list(hah, wow, woow)
 
scala> l
res3: list[string] = list(hello, hi, hah, wow, woow)

返回去掉l后两个元素的新列表

scala> l.dropright(2)
res5: list[string] = list(hello, hi, hah)
 
scala> l
res6: list[string] = list(hello, hi, hah, wow, woow)

判断l是否存在某个元素

scala> l.exists(s => s == "hah")
res7: boolean = true

滤出长度为3的元素

scala> l.filter(s => s.length == 3)
res8: list[string] = list(hah, wow)

判断所有元素是否以“h”打头

scala> l.forall(s => s.startswith("h"))
res10: boolean = false

判断所有元素是否以“h”结尾

scala> l.forall(s => s.endswith("w"))
res11: boolean = false

打印每个元素

scala> l.foreach(s => print(s + ' '))
hello hi hah wow woow

取出第一个元素

scala> l.head
res17: string = hello

取出最后一个元素

scala> l.last
res20: string = woow

剔除最后一个元素,生成新列表

scala> l.init
res18: list[string] = list(hello, hi, hah, wow)

剔除第一个元素,生成新列表

scala> l.tail
res49: list[string] = list(hi, hah, wow, woow)

判断列表是否为空

scala> l.isempty
res19: boolean = false

获得列表长度

scala> l.length
res21: int = 5

修改每个元素,再反转每个元素形成新列表

scala> l.map(s => {val s1 = s + " - 01"; s1.reverse})
res29: list[string] = list(10 - olleh, 10 - ih, 10 - hah, 10 - wow, 10 - woow)

生成用逗号隔开的字符串

scala> l.mkstring(", ")
res30: string = hello, hi, hah, wow, woow

反序生成新列表

scala> l.reverse
res41: list[string] = list(woow, wow, hah, hi, hello)

按字母递增排序

scala> l.sortwith(_.compareto(_) < 0)
res48: list[string] = list(hah, hello, hi, woow, wow)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网