Scala - Seq

First of all, let me just point to the fact that in Scala, when we think List we mean Seq.

这个需要进一步多看一些文章.来说明seq的优势.以及list等其他集合类型的适用场景

foreach

val seq =Seq(1,2,3,4,5)
seq.foreach(item => println(item))

map

val seq2 = seq.map(_+1)

map 和foreach 主要区别是map是返回值的,foreach返回是Unit (类似void)类型

filter

val seq3 = seq.filter(_>2)

filter 是返回满足条件的

exist

scala> seq.exists(_>10)
res13: Boolean = false

scala> seq.exists(_>9)
res14: Boolean = false

scala> seq.exists(_>1)
res15: Boolean = true

看是否有满足条件的元素

find

scala> seq.find(_ == 3)
res16: Option[Int] = Some(3)

scala> seq.find(_ == 30)
res17: Option[Int] = None

find返回的是Option类型,可能找到了,可能没找到

apply

scala> seq(1)
res18: Int = 2

scala> seq(0)
res19: Int = 1

seq 是Seq类型,直接()就是执行apply方法.带入index(key)返回值

其他的以后补充