List列表 #

一、List 基础 #

1.1 创建 List #

scala
val list1 = List(1, 2, 3, 4, 5)
val list2 = 1 :: 2 :: 3 :: Nil
val list3 = Nil
val list4 = List.empty[Int]
val list5 = List.fill(5)(0)
val list6 = List.range(1, 10)
val list7 = List.range(1, 10, 2)
val list8 = List.tabulate(5)(n => n * n)

1.2 List 特点 #

  • 不可变
  • 有序
  • 可重复
  • 单向链表结构

1.3 基本访问 #

scala
val list = List(1, 2, 3, 4, 5)

list.head
list.last
list.tail
list.init
list(0)
list(2)
list.take(3)
list.takeRight(2)
list.drop(2)
list.dropRight(2)

二、List 操作 #

2.1 添加元素 #

scala
val list = List(2, 3, 4)

val list1 = 1 :: list
val list2 = list :+ 5
val list3 = 0 +: list
val list4 = list ++ List(5, 6)
val list5 = List(0, 1) ++: list

2.2 连接列表 #

scala
val list1 = List(1, 2, 3)
val list2 = List(4, 5, 6)

val combined1 = list1 ++ list2
val combined2 = list1 ::: list2
val combined3 = List.concat(list1, list2)

2.3 反转列表 #

scala
val list = List(1, 2, 3, 4, 5)

list.reverse
list.reverse_:::(List(0))

三、常用方法 #

3.1 查找 #

scala
val list = List(1, 2, 3, 4, 5)

list.find(_ > 3)
list.filter(_ > 3)
list.filterNot(_ > 3)
list.takeWhile(_ < 4)
list.dropWhile(_ < 3)
list.span(_ < 3)
list.partition(_ % 2 == 0)

3.2 检查 #

scala
val list = List(1, 2, 3, 4, 5)

list.isEmpty
list.nonEmpty
list.contains(3)
list.exists(_ > 3)
list.forall(_ > 0)
list.startsWith(List(1, 2))
list.endsWith(List(4, 5))

3.3 转换 #

scala
val list = List(1, 2, 3, 4, 5)

list.map(_ * 2)
list.flatMap(n => List(n, n * 2))
list.flatten
list.grouped(2).toList
list.sliding(3).toList
list.zip(List("a", "b", "c", "d", "e"))
list.zipWithIndex

3.4 聚合 #

scala
val list = List(1, 2, 3, 4, 5)

list.sum
list.product
list.min
list.max
list.minBy(_.abs)
list.maxBy(_.abs)
list.reduce(_ + _)
list.reduceLeft(_ - _)
list.reduceRight(_ - _)
list.fold(0)(_ + _)
list.foldLeft(0)(_ + _)
list.foldRight(0)(_ + _)

3.5 排序 #

scala
val list = List(3, 1, 4, 1, 5, 9, 2, 6)

list.sorted
list.sorted(Ordering[Int].reverse)
list.sortBy(_.abs)
list.sortWith((a, b) => a > b)

3.6 分组 #

scala
val list = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

list.groupBy(_ % 2)
list.grouped(3).toList
list.sliding(3).toList

四、模式匹配 #

4.1 基本匹配 #

scala
val list = List(1, 2, 3, 4, 5)

val result = list match
  case Nil => "Empty"
  case head :: Nil => s"Single: $head"
  case head :: tail => s"Head: $head, Tail: $tail"

4.2 提取元素 #

scala
val list = List(1, 2, 3, 4, 5)

val result = list match
  case List(a, b, c) => s"Three elements: $a, $b, $c"
  case a :: b :: rest => s"First two: $a, $b, rest: $rest"
  case _ => "Other"

4.3 递归处理 #

scala
def sum(list: List[Int]): Int = list match
  case Nil => 0
  case head :: tail => head + sum(tail)

def length(list: List[?]): Int = list match
  case Nil => 0
  case _ :: tail => 1 + length(tail)

五、ListBuffer #

5.1 创建 ListBuffer #

scala
import scala.collection.mutable.ListBuffer

val buffer = ListBuffer(1, 2, 3)
val empty = ListBuffer.empty[Int]

5.2 添加元素 #

scala
import scala.collection.mutable.ListBuffer

val buffer = ListBuffer(1, 2, 3)

buffer += 4
buffer += (5, 6)
buffer ++= List(7, 8)
buffer.prepend(0)
buffer.append(9)

5.3 删除元素 #

scala
import scala.collection.mutable.ListBuffer

val buffer = ListBuffer(1, 2, 3, 4, 5)

buffer -= 3
buffer.remove(0)
buffer.remove(1, 2)
buffer.clear()

5.4 转换为 List #

scala
import scala.collection.mutable.ListBuffer

val buffer = ListBuffer(1, 2, 3, 4, 5)
val list = buffer.toList

六、List 实战 #

6.1 队列实现 #

scala
class Queue[T]:
  private var front: List[T] = Nil
  private var back: List[T] = Nil
  
  def enqueue(item: T): Unit =
    back = item :: back
  
  def dequeue(): Option[T] =
    if front.isEmpty then
      front = back.reverse
      back = Nil
    front match
      case Nil => None
      case head :: tail =>
        front = tail
        Some(head)
  
  def isEmpty: Boolean = front.isEmpty && back.isEmpty

val queue = Queue[Int]()
queue.enqueue(1)
queue.enqueue(2)
println(queue.dequeue())
println(queue.dequeue())

6.2 栈实现 #

scala
class Stack[T]:
  private var items: List[T] = Nil
  
  def push(item: T): Unit =
    items = item :: items
  
  def pop(): Option[T] = items match
    case Nil => None
    case head :: tail =>
      items = tail
      Some(head)
  
  def peek: Option[T] = items.headOption
  
  def isEmpty: Boolean = items.isEmpty

val stack = Stack[Int]()
stack.push(1)
stack.push(2)
println(stack.pop())
println(stack.pop())

6.3 数据处理 #

scala
case class Person(name: String, age: Int, salary: Double)

val people = List(
  Person("Alice", 25, 50000),
  Person("Bob", 35, 75000),
  Person("Charlie", 28, 60000),
  Person("David", 45, 90000)
)

val adults = people.filter(_.age >= 30)
val names = people.map(_.name)
val totalSalary = people.map(_.salary).sum
val byAge = people.groupBy(_.age >= 30)
val sorted = people.sortBy(_.age)

七、性能考虑 #

7.1 时间复杂度 #

操作 时间复杂度
head O(1)
tail O(1)
:: (prepend) O(1)
:+ (append) O(n)
apply(n) O(n)
length O(n)

7.2 优化建议 #

scala
val list = List(1, 2, 3)

val good = 0 :: list
val bad = list :+ 4

val good2 = list.reverse
val bad2 = list.reverse.reverse

八、总结 #

List 方法速查 #

方法 说明
head 第一个元素
tail 除第一个外的元素
:: 前置添加
:+ 后置添加
++ 连接
map 映射
filter 过滤
fold 折叠
groupBy 分组

选择建议 #

场景 推荐
频繁头部操作 List
频繁尾部操作 ListBuffer 或 Vector
随机访问 Vector
队列 Queue

下一步,让我们学习 Set集合

最后更新:2026-03-27