val x = Vector(1, 2, 3)
x.sum // 6
x.filter(_ > 1) // Vector(2, 3)
x.map(_ * 2) // Vector(2, 4, 6)
x.takeWhile(_ < 3) // Vector(1, 2)
immutable :
ArraySeq属于IndexedSeq,底层数组实现,随机查找性能高,写操作需要线性时间
LazyList属于LinearSeq,是链表,但是lazy
List属于LinearSeq,适合prepending 元素,操作表的投或者尾
Queue属于LinearSeq,先进先出的数据结构,适用于不可变及可变版本
Range属于IndexedSeq
Vector
mutable :
Array属于IndexedSeq,
ArrayBuffer
import scala.util.Random
// List
val xs = List(1,2,3,4,5)
val ys = Random.shuffle(xs) // result will be shuffled, like List(4,1,3,2,5)
// also works with other sequences
val x = Random.shuffle(Vector(1,2,3,4,5)) // x: Vector(5,3,4,1,2)
val x = Random.shuffle(Array(1,2,3,4,5)) // x: ArraySeq(1,3,2,4,5)
import scala.collection.mutable.ArrayBuffer
val x = Random.shuffle(ArrayBuffer(1,2,3,4,5)) // x: ArrayBuffer(4,2,3,1,5)
import scala.util.Random
val randomNumber = getRandomElement(List(1,2,3))
val randomString = getRandomElement(List(“a”, “b”, “c”))
Methods like dropRight and takeRight will perform slowly on linear sequences like a List. If you need to use these methods with large sequences, use an indexed sequence like Vector instead.
val nums = Vector(1, 2, 3, 4, 5)
nums.head // 1
nums.headOption // Some(1)
nums.init // Vector(1, 2, 3, 4)
nums.tail // Vector(2, 3, 4, 5)
nums.last // 5
nums.lastOption // Some(5)
head, init, tail, and last will throw a java.lang.UnsupportedOperationException on empty sequences.
val xs = List(15, 5, 25, 20, 10)
val ys = xs.partition(_ > 10) // ys: (List(15, 25, 20), List(5, 10))
val ys = xs.partition(_ < 25) // ys: (List(15, 5, 20, 10), List(25))
val ys = xs.span(_ < 20) // ys: (List(15, 5), List(25, 20, 10))
val ys = xs.span(_ > 10) // ys: (List(15), List(5, 25, 20, 10))
val states = Map(
“AK” -> “Alaska”,
“IL” -> “Illinois”,
“KY” -> “Kentucky”
)
states.values.exists(.contains(“ucky”))//不要使用,产生中间数据消耗内存
states.valuesIterator.exists(.contains(“ucky”)) // 建议使用
keysIterator and valuesIterator不会创建中间对象建议使用
val x = LinkedHashMap(states .toSeq.sortBy(_.1):*)