The sequence traits Seq, IndexedSeq, and LinearSeq
TheSeq trait represents sequences. A sequence is a kind of iterable that has alength
and whose elements have fixed index positions, starting from0
.
The operations on sequences, summarized in the table below, fall into the following categories:
- Indexing and length operations
apply
,isDefinedAt
,length
,indices
, andlengthCompare
. For aSeq
, theapply
operation means indexing; hence a sequence of typeSeq[T]
is a partial function that takes anInt
argument (an index) and which yields a sequence element of typeT
. In other wordsSeq[T]
extendsPartialFunction[Int, T]
. The elements of a sequence are indexed from zero up to thelength
of the sequence minus one. Thelength
method on sequences is an alias of thesize
method of general collections. ThelengthCompare
method allows you to compare the lengths of a sequences with an Int or with anIterable
even if the sequences has infinite length. - Index search operations
indexOf
,lastIndexOf
,indexOfSlice
,lastIndexOfSlice
,indexWhere
,lastIndexWhere
,segmentLength
, which return the index of an element equal to a given value or matching some predicate. - Addition operations
prepended
,prependedAll
,appended
,appendedAll
,padTo
, which return new sequences obtained by adding elements at the front or the end of a sequence. - Update operations
updated
,patch
, which return a new sequence obtained by replacing some elements of the original sequence. - Sorting operations
sorted
,sortWith
,sortBy
, which sort sequence elements according to various criteria. - Reversal operations
reverse
,reverseIterator
, which yield or process sequence elements in reverse order. - Comparisons
startsWith
,endsWith
,contains
,containsSlice
,corresponds
,search
, which relate two sequences or search an element in a sequence. - Multiset operations
intersect
,diff
,distinct
,distinctBy
, which perform set-like operations on the elements of two sequences or remove duplicates.
If a sequence is mutable, it offers in addition a side-effectingupdate
method, which lets sequence elements be updated. As always in Scala, syntax likeseq(idx) = elem
is just a shorthand forseq.update(idx, elem)
, soupdate
gives convenient assignment syntax for free. Note the difference betweenupdate
andupdated
.update
changes a sequence element in place, and is only available for mutable sequences.updated
is available for all sequences and always returns a new sequence instead of modifying the original.
Operations in Class Seq
WHAT IT IS | WHAT IT DOES |
---|---|
Indexing and Length: | |
xs(i) | (or, written out,xs.apply(i) ). The element ofxs at indexi . |
xs.isDefinedAt(i) | Tests whetheri is contained inxs.indices . |
xs.length | The length of the sequence (same assize ). |
xs.lengthCompare(n) | Returns-1 ifxs is shorter thann ,+1 if it is longer, and0 if it is of lengthn . Works even if the sequence is infinite, for exampleLazyList.from(1).lengthCompare(42) returns a positive value. |
xs.indices | The index range ofxs , extending from0 toxs.length - 1 . |
Index Search: | |
xs.indexOf(x) | The index of the first element inxs equal tox (several variants exist). |
xs.lastIndexOf(x) | The index of the last element inxs equal tox (several variants exist). |
xs.indexOfSlice(ys) | The first index ofxs such that successive elements starting from that index form the sequenceys . |
xs.lastIndexOfSlice(ys) | The last index ofxs such that successive elements starting from that index form the sequenceys . |
xs.indexWhere(p) | The index of the first element in xs that satisfiesp (several variants exist). |
xs.segmentLength(p, i) | The length of the longest uninterrupted segment of elements inxs , starting withxs(i) , that all satisfy the predicatep . |
Additions: | |
xs.prepended(x) or x +: xs | A new sequence that consists ofx prepended toxs . |
xs.prependedAll(ys) or ys ++: xs | A new sequence that consists of all the elements ofys prepended toxs . |
xs.appended(x) or xs :+ x | A new sequence that consists ofx appended toxs . |
xs.appendedAll(ys) or xs :++ ys | A new sequence that consists of all the elements ofys appended toxs . |
xs.padTo(len, x) | The sequence resulting from appending the valuex toxs until lengthlen is reached. |
Updates: | |
xs.patch(i, ys, r) | The sequence resulting from replacingr elements ofxs starting withi by the patchys . |
xs.updated(i, x) | A copy ofxs with the element at indexi replaced byx . |
xs(i) = x | (or, written out,xs.update(i, x) , only available formutable.Seq s). Changes the element ofxs at indexi tox . |
Sorting: | |
xs.sorted | A new sequence obtained by sorting the elements ofxs using the standard ordering of the element type ofxs . |
xs.sortWith(lt) | A new sequence obtained by sorting the elements ofxs usinglt as comparison operation. |
xs.sortBy(f) | A new sequence obtained by sorting the elements ofxs . Comparison between two elements proceeds by mapping the functionf over both and comparing the results. |
Reversals: | |
xs.reverse | A sequence with the elements ofxs in reverse order. |
xs.reverseIterator | An iterator yielding all the elements ofxs in reverse order. |
Comparisons: | |
xs.sameElements(ys) | A test whetherxs andys contain the same elements in the same order |
xs.startsWith(ys) | Tests whetherxs starts with sequenceys (several variants exist). |
xs.endsWith(ys) | Tests whetherxs ends with sequenceys (several variants exist). |
xs.contains(x) | Tests whetherxs has an element equal tox . |
xs.search(x) | Tests whether a sorted sequencexs has an element equal tox , possibly in a more efficient way thanxs.contains(x) . |
xs.containsSlice(ys) | Tests whetherxs has a contiguous subsequence equal toys . |
xs.corresponds(ys)(p) | Tests whether corresponding elements ofxs andys satisfy the binary predicatep . |
Multiset Operations: | |
xs.intersect(ys) | The multi-set intersection of sequencesxs andys that preserves the order of elements inxs . |
xs.diff(ys) | The multi-set difference of sequencesxs andys that preserves the order of elements inxs . |
xs.distinct | A subsequence ofxs that contains no duplicated element. |
xs.distinctBy(f) | A subsequence ofxs that contains no duplicated element after applying the transforming functionf . For instance,List("foo", "bar", "quux").distinctBy(_.length) == List("foo", "quux") |
TraitSeq has two subtraitsLinearSeq, andIndexedSeq. These do not add any new operations to the immutable branch, but each offers different performance characteristics: A linear sequence has efficienthead
andtail
operations, whereas an indexed sequence has efficientapply
,length
, and (if mutable)update
operations. Frequently used linear sequences arescala.collection.immutable.List
andscala.collection.immutable.LazyList
. Frequently used indexed sequences arescala.Array
andscala.collection.mutable.ArrayBuffer
. TheVector
class provides an interesting compromise between indexed and linear access. It has both effectively constant time indexing overhead and constant time linear access overhead. Because of this, vectors are a good foundation for mixed access patterns where both indexed and linear accesses are used. You’ll learn more on vectorslater.
On the mutable branch,IndexedSeq
adds operations for transforming its elements in place (by contrast withtransformation operations such asmap
andsort
, available on the rootSeq
, which return a new collectioninstance).
Operations in Class mutable.IndexedSeq
WHAT IT IS | WHAT IT DOES |
---|---|
Transformations: | |
xs.mapInPlace(f) | Transforms all the elements ofxs by applying thef function to each of them. |
xs.sortInPlace() | Sorts the collectionxs . |
xs.sortInPlaceWith(c) | Sorts the collectionxs according to the given comparison functionc . |
xs.sortInPlaceBy(f) | Sorts the collectionxs according to an ordering defined on the result of the application of the functionf to each element. |
Buffers
An important sub-category of mutable sequences isBuffer
s. They allow not only updates of existing elements but also element additions, insertions and removals. The principal new methods supported by a buffer areappend
andappendAll
for element addition at the end,prepend
andprependAll
for addition at the front,insert
andinsertAll
for element insertions, as well asremove
,subtractOne
andsubtractAll
for element removal. These operations are summarized in the following table.
Two often used implementations of buffers areListBuffer
andArrayBuffer
. As the name implies, aListBuffer
is backed by aList
, and supports efficient conversion of its elements to aList
, whereas anArrayBuffer
is backed by an array, and can be quickly converted into one.
Operations in Class Buffer
WHAT IT IS | WHAT IT DOES |
---|---|
Additions: | |
buf.append(x) or buf += x | Appends elementx to buffer, and returnsbuf itself as result. |
buf.appendAll(xs) or buf ++= xs | Appends all elements inxs to buffer. |
buf.prepend(x) or x +=: buf | Prepends elementx to buffer. |
buf.prependAll(xs) or xs ++=: buf | Prepends all elements inxs to buffer. |
buf.insert(i, x) | Inserts elementx at indexi in buffer. |
buf.insertAll(i, xs) | Inserts all elements inxs at indexi in buffer. |
buf.padToInPlace(n, x) | Appends elementx to buffer until it hasn elements in total. |
Removals: | |
buf.subtractOne(x) or buf -= x | Removes elementx from buffer. |
buf.subtractAll(xs) or buf --= xs | Removes elements inxs from buffer. |
buf.remove(i) | Removes element at indexi from buffer. |
buf.remove(i, n) | Removesn elements starting at indexi from buffer. |
buf.trimStart(n) | Removes firstn elements from buffer. |
buf.trimEnd(n) | Removes lastn elements from buffer. |
buf.clear() | Removes all elements from buffer. |
Replacement: | |
buf.patchInPlace(i, xs, n) | Replaces (at most)n elements of buffer by elements inxs , starting from indexi in buffer. |
Cloning: | |
buf.clone() | A new buffer with the same elements asbuf . |
Contributors to this page:
Contents
- Introduction
- Mutable and Immutable Collections
- Trait Iterable
- The sequence traits Seq, IndexedSeq, and LinearSeq
- Sets
- Maps
- Concrete Immutable Collection Classes
- Concrete Mutable Collection Classes
- Arrays
- Strings
- Performance Characteristics
- Equality
- Views
- Iterators
- Creating Collections From Scratch
- Conversions Between Java and Scala Collections
- Conversion Between Option and the Collections