-
Notifications
You must be signed in to change notification settings - Fork 9
Collection 函数示例
Song Kun edited this page Feb 3, 2018
·
3 revisions
创建:
// sequence: Seq[Int] = List(1, 2, 3)
val sequence = Seq(1, 2, 3)
-
Seq
顺序固定 -
Seq
默认实现为List
,所以sequence
类型为Seq[Int]
,但实现为List[Int]
索引访问:
// res0: Int = 1
sequence(0)
// res1: Int = 3
sequence.apply(2) // sugared syntax
-
sequence(index)
索引为Int
,从 0 开始
头尾:
// res2: Int = 1
sequence.head
// None
Seq().headOption
// res3: Seq[Int] = List(2, 3)
sequence.tail
- 在空
Seq
执行head
tail
会抛异常,可以使用headOption
取代head
,但tail
没有tailOption
版本
搜索元素:
// 使用 == 查找
sequence.contains(2)
// res0: Option[Int] = Some(2)
sequence.find(_ > 1)
// res0: Seq[Int] = List(2, 3)
sequence.filter(_ > 1)
-
find
仅返回predicate
为true
的第一个元素,且返回类型为Option
-
filter
返回所有满足predicate
的元素组成的List
排序:
val sequence = Seq(1, 2, 3, -1)
// res0: Seq[Int] = List(-1, 1, 2, 3)
sequence.sortWith(_ < _)
-
sortWith
参数为二元函数,接受两个List
元素作为参数,类似 Java 的comparator
添加:
// res0: Seq[Int] = List(0, 1, 2, 3)
0 +: sequence
// res0: Seq[Int] = List(1, 2, 3, 4)
sequence :+ 4
// res0: Seq[Int] = List(1, 2, 3, 4, 5, 6)
sequence ++ Seq(4, 5, 6)
-
+:
头部添加 -
:+
尾部添加 -
++
Seq
拼接
List
为链表,是 Seq
的默认实现。
链表拼接:
val x1 = 1 :: 2 :: Nil
val x2 = 3 :: 4 :: Nil
x1 ::: x2
- 对应
Seq
的++
函数