1. Scala的集合体系结构

Scala中的集合体系主要包括(结构跟Java相似):

  • Iterable(所有集合trait的根trait)
  • Seq(Range、ArrayBuffer、List等)
  • Set(HashSet、LinkedHashSet、SortedSet等)
  • Map (HashMap、SortedMap、LinkedHashMap等)

Scala中的集合分为可变和不可变两类集合,分别对应scala.collection.mutable和scala.collection.immutable两个包。

2. List

List代表一个不可变的列表。

  • List有head和tail,head代表List的第一个元素,tail代表第一个元素之后的所有元素。
scala> val list = List(1, 2, 3, 4)
list: List[Int] = List(1, 2, 3, 4)
scala> list.head
res33: Int = 1
scala> list.tail
res34: List[Int] = List(2, 3, 4)

  
案例:用递归函数给List中每个元素都加上指定的前缀并打印

// 如果List只有一个元素,那么他的tail就是Nil
def decorator(list: List[Int], prefix: String){
if (list != Nil) {
println(prefix + list.head)
decorator(list.tail, prefix)
}
}
scala> decorator(list, "+")
+1
+2
+3
+4

  • List有特殊的::操作符,可以用于将head和tail合并成一个List。
scala> list
res37: List[Int] = List(1, 2, 3, 4)
scala> 0::list
res38: List[Int] = List(0, 1, 2, 3, 4)

该操作符在Spark源码中有体现

3. LinkedList

LinkedList代表一个可变的列表,其elem和next属性类似于List的head和tail。

案例:使用while循环将LinkedList中每个一个元素乘以二。

val list = scala.collection.mutable.LinkedList(1,2,3,4,5,6,7,8,9)
var currentList = list
var first = true
while( currentList !=Nil && currentList.next != Nil){
if(first) { currentList.elem *= 2; first = false}
currentList = currentList.next.next
if(currentList != Nil) currentList.elem *= 2
}
list: scala.collection.mutable.LinkedList[Int] = LinkedList(2, 2, 6, 4, 10, 6, 14, 8, 18)

相关文章:

  • 2022-12-23
  • 2021-09-06
  • 2022-03-09
  • 2021-08-27
  • 2022-01-11
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-11-09
  • 2021-06-24
  • 2021-04-16
  • 2021-07-22
  • 2021-12-16
  • 2022-12-23
相关资源
相似解决方案