ВУЗ: Не указан

Категория: Не указан

Дисциплина: Не указана

Добавлен: 02.01.2026

Просмотров: 3437

Скачиваний: 0

ВНИМАНИЕ! Если данный файл нарушает Ваши авторские права, то обязательно сообщите нам.

Section 24.5

Chapter 24 · The Scala Collections API

549

Table 24.3 · continued

Updates:

 

xs patch (i, ys, r)

The sequence resulting from replacing r elements

 

of xs starting with i by the patch ys.

xs updated (i, x)

A copy of xs with the element at index i replaced

 

by x.

xs(i) = x

(or, written out, xs.update(i, x), only available

 

for mutable.Seqs) Changes the element of xs at

 

index i to y.

Sorting:

 

xs.sorted

A new sequence obtained by sorting the elements

 

of xs using the standard ordering of the element

 

type of xs.

xs sortWith lessThan

A new sequence obtained by sorting the elements

 

of xs, using lessThan as comparison operation.

xs sortBy f

A new sequence obtained by sorting the elements

 

of xs. Comparison between two elements

 

proceeds by mapping the function f over both

 

and comparing the results.

Reversals:

 

xs.reverse

A sequence with the elements of xs in reverse

 

order.

xs.reverseIterator

An iterator yielding all the elements of xs in

 

reverse order.

xs reverseMap f

A sequence obtained by mapping f over the

 

elements of xs in reverse order.

Comparisons:

 

xs startsWith ys

Tests whether xs starts with sequence ys (several

 

variants exist).

xs endsWith ys

Tests whether xs ends with sequence ys (several

 

variants exist).

xs contains x

Tests whether xs has an element equal to x.

xs containsSlice ys

Tests whether xs has a contiguous subsequence

 

equal to ys.

(xs corresponds ys)(p)

Tests whether corresponding elements of xs and

 

ys satisfy the binary predicate p.

Cover · Overview · Contents · Discuss · Suggest · Glossary · Index


Section 24.5

Chapter 24 · The Scala Collections API

550

 

Table 24.3 · continued

Multiset operations:

 

xs intersect ys

The multi-set intersection of sequences xs and ys

 

that preserves the order of elements in xs.

xs diff ys

The multi-set difference of sequences xs and ys

 

that preserves the order of elements in xs.

xs union ys

Multiset union; same as xs ++ ys.

xs.distinct

A subsequence of xs that contains no duplicated

 

element.

Each Seq trait has two subtraits, LinearSeq and IndexedSeq. These do not add any new operations, but each offers different performance characteristics. A linear sequence has efficient head and tail operations, whereas an indexed sequence has efficient apply, length, and (if mutable) update operations. List is a frequently used linear sequence, as is Stream. Two frequently used indexed sequences are Array and ArrayBuffer. The Vector 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 if this, vectors are a good foundation for mixed access patterns where both indexed and linear accesses are used. More on vectors in Section 24.9.

Buffers

An important sub-category of mutable sequences is buffers. Buffers allow not only updates of existing elements but also element insertions, element removals, and efficient additions of new elements at the end of the buffer. The principal new methods supported by a buffer are += and ++=, for element addition at the end, +=: and ++=: for addition at the front, insert and insertAll for element insertions, as well as remove and -= for element removal. These operations are summarized in Table 24.4.

Two Buffer implementations that are commonly used are ListBuffer and ArrayBuffer. As the name implies, a ListBuffer is backed by a List and supports efficient conversion of its elements to a List, whereas an ArrayBuffer is backed by an array, and can be quickly converted into one. You saw a glimpse of the implementation of ListBuffer in Section 22.2.

Cover · Overview · Contents · Discuss · Suggest · Glossary · Index



Section 24.6

Chapter 24 · The Scala Collections API

551

Table 24.4 · Operations in trait Buffer

What it is

What it does

Additions:

 

buf += x

Appends element x to buffer buf, and returns buf

 

itself as result

buf += (x, y, z)

Appends given elements to buffer

buf ++= xs

Appends all elements in xs to buffer

x +=: buf

Prepends element x to buffer

xs ++=: buf

Prepends all elements in xs to buffer

buf insert (i, x)

Inserts element x at index i in buffer

buf insertAll (i, xs)

Inserts all elements in xs at index i in buffer

Removals:

 

buf -= x

Removes element x from buffer

buf remove i

Removes element at index i from buffer

buf remove (i, n)

Removes n elements starting at index i from

 

buffer

buf trimStart n

Removes first n elements from buffer

buf trimEnd n

Removes last n elements from buffer

buf.clear()

Removes all elements from buffer

Cloning:

 

buf.clone

A new buffer with the same elements as buf

24.6 Sets

Sets are Iterables that contain no duplicate elements. The operations on sets are summarized in Table 24.5 for general sets and Table 24.6 for mutable sets. They fall into the following categories:

Tests contains, apply, and subsetOf. The contains method indicates whether a set contains a given element. The apply method for a set is the same as contains, so set(elem) is the same as set contains elem. That means sets can also be used as test functions that return true for the elements they contain. For example:

Cover · Overview · Contents · Discuss · Suggest · Glossary · Index


Section 24.6

Chapter 24 · The Scala Collections API

552

scala> val fruit = Set("apple", "orange", "peach", "banana") fruit: scala.collection.immutable.Set[java.lang.String] =

Set(apple, orange, peach, banana)

scala> fruit("peach") res7: Boolean = true

scala> fruit("potato") res8: Boolean = false

Additions + and ++, which add one or more elements to a set, yielding a new set as a result.

Removals - and --, which remove one or more elements from a set, yielding a new set.

Set operations for union, intersection, and set difference. These set operations exist in two forms: alphabetic and symbolic. The alphabetic versions are intersect, union, and diff, whereas the symbolic versions are &, |, and &~. The ++ that Set inherits from Traversable can be seen as yet another alias of union or |, except that ++ takes a Traversable argument whereas union and | take sets.

Table 24.5 · Operations in trait Set

What it is

What it does

Tests:

 

xs contains x

Tests whether x is an element of xs

xs(x)

Same as xs contains x

xs subsetOf ys

Tests whether xs is a subset of ys

Additions:

 

xs + x

The set containing all elements of xs as well as x

xs + (x, y, z)

The set containing all elements of xs as well as

 

the given additional elements

xs ++ ys

The set containing all elements of xs as well as

 

all elements of ys

Cover · Overview · Contents · Discuss · Suggest · Glossary · Index