Skip to content

Collection 函数示例

Song Kun edited this page Feb 3, 2018 · 3 revisions

Seq

创建:

// 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 仅返回 predicatetrue 的第一个元素,且返回类型为 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

List 为链表,是 Seq 的默认实现。

链表拼接:

val x1 = 1 :: 2 :: Nil
val x2 = 3 :: 4 :: Nil

x1 ::: x2
  • 对应 Seq++ 函数
Clone this wiki locally