Scala/Колекції

Матеріал з Вікіпідручника

Колекціїї знаходяться в пакеті scala.collection та дочірніх пакетах mutable (змінюваний), immutable (незмінний), and generic (загальний).

Більшість колекцій мають три варіанти, які відрізняються мінливістю (mutability) і розташовані відповідно у пакетах scala.collection, scala.collection.immutable і scala.collection.mutable.

Колекції із scala.collection.immutable гарантовано незмінні, у scala.collection.mutable - змінні. Колекції пакету scala.collection містять базові реалізації, наприклад, collection.IndexedSeq [T] є суперкласом для <tt">collection.immutable.IndexedSeq [T] і collection.mutable.IndexedSeq [T].

За замовчуванням, Scala завжди вибирає незмінні колекцій. Щоб отримати змінювані версії необхідно написати або імпортувати явно клас із пакету collection.mutable.

Основні колекції[ред.]

  • Traversable
    • Iterable
      • Seq
        • IndexedSeq
          • Vector
          • ResizableArray
          • GenericArray
        • LinearSeq
          • MutableList
          • List
          • Stream
        • Buffer
          • ListBuffer
          • ArrayBuffer
      • Set
        • SortedSet
          • TreeSet
        • HashSet (mutable)
        • LinkedHashSet
        • HashSet (immutable)
        • BitSet
        • EmptySet, Set1, Set2, Set3, Set4
      • Map
        • SortedMap
          • TreeMap
        • HashMap (mutable)
        • LinkedHashMap (mutable)
        • HashMap (immutable)
        • EmptyMap, Map1, Map2, Map3, Map4

Traversable[ред.]

Типаж (Trait) Traversable - вершина ієрархії класів Scala. Має єдину абстрактну операцію — foreach:

 def foreach[U](f: Elem => U)
Метод Результат
Абстрактний метод:
xs foreach f Виконує функцію f для кожного елемента xs
Додавання:
xs ++ ys Колекція що складається з елементів xs і ys. ys є колекцією типу TraversableOnce, тобто Traversable або Iterator
Відображення:
xs map f Колекція одержана застосуванням функції f до кожного елемента xs
xs flatMap f Колекція одержана застосуваням функції f, що повертає колекцію, до кожного елемента xs і конкатенацією результатів
xs collect f Колекція одержана застосуваням часткової функції f до кожного елемента xs, на якому вона визначена і об'єднанням результатів
Перетворення:
xs.toArray Перетворює колекцію у масив
xs.toList Перетворює колекцію у список
xs.toIterable Перетворює колекцію у iterable
xs.toSeq Перетворює колекцію у послідовність
xs.toIndexedSeq Перетворює колекцію у індексовану послідовність
xs.toStream Перетворює колекцію у ліниво обчислюваний потік
xs.toSet Перетворює колекцію у множину
xs.toMap Перетворює колекцію пар ключ/значення у відображення
Копіювання:
xs copyToBuffer buf копіює всі елементи колекції у буфер buf
xs copyToArray(arr, s, len) Copies at most len arr starting at index s. The last two arguments are optional
Size info:
xs.isEmpty Tests whether the collection is empty
xs.nonEmpty Tests whether the collection contains elements
xs.size The number of elements in the collection
xs.hasDefiniteSize True if xs is known to have finite size
Element Retrieval:
xs.head The first element of the collection (or, some element, if no order is defined)
xs.headOption The first element of xs in an option value, or None if xs is empty
xs.last The last element of the collection (or, some element, if no order is defined)
xs.lastOption The last element of xs in an option value, or None if xs is empty
xs find p An option containing the first element in xs that satisfies p, or None is no element qualifies
Subcollections:
xs.tail The rest of the collection except xs.head
xs.init The rest of the collection except xs.last
xs slice (from, to) A collection consisting of elements in some index

range of xs (from from up to, and excluding to) xs take n A collection consisting of the first n elements of xs (or, some arbitrary n elements, if no order is defined)

xs drop n The rest of the collection except xs take n
xs takeWhile p The longest prefix of elements in the collection that all satisfy p
xs dropWhile p The collection without the longest prefix of elements that all satisfy p
xs filter p The collection consisting of those elements of xs that satisfy the predicate p
xs withFilter p A non-strict filter of this collection. All operations on the resulting filter will only apply to those elements of xs for which the condition p is true
xs filterNot p The collection consisting of those elements of xs that do not satisfy the predicate p
Subdivisions:
xs splitAt n Split xs at a position, giving the pair of collections (xs take n, xs drop n)
xs span p Split xs according to a predicate, giving the pair

of collections (xs takeWhile p, xs.dropWhile p)

xs partition p Split xs into a pair of two collections; one with

elements that satisfy the predicate p, the other with elements that do not, giving the pair of collections (xs filter p, xs.filterNot p)

xs groupBy f Partition xs into a map of collections according to a discriminator function f
Element Conditions:
xs forall p A boolean indicating whether the predicate p holds for all elements of xs
xs exists p A boolean indicating whether the predicate p holds for some element in xs
xs count p The number of elements in xs that satisfy the predicate p
Folds:
(z /: xs)(op) Apply binary operation op between successive elements of xs, going left to right and starting with z
(xs :\ z)(op) Apply binary operation op between successive elements of xs, going right to left and starting with z
xs.foldLeft(z)(op) Same as (z /: xs)(op)
xs.foldRight(z)(op) Same as (xs :\ z)(op)
xs reduceLeft op Apply binary operation op between successive elements of non-empty collection xs, going left to right
xs reduceRight op Apply binary operation op between successive elements of non-empty collection xs, going right to left
Specific Folds:
xs.sum The sum of the numeric element values of collection xs
xs.product The product of the numeric element values of collection xs
xs.min The minimum of the ordered element values of collection xs
xs.max The maximum of the ordered element values of collection xs
Strings:
xs addString (b, start, sep, end) Adds a string to StringBuilder b that shows all elements of xs between separators sep enclosed in strings start and end. start, sep, end are all optional
xs mkString (start, sep, end) Converts the collection to a string that shows all elements of xs between separators sep enclosed in strings start and end. start, sep, end are all optional
xs.stringPrefix The collection name at the beginning of the string returned from xs.toString
Views:
xs.view Produces a view over xs
xs view (from, to) Produces a view that represents the elements in some index range of xs

Iterable[ред.]

Має абстрактний метод — iterator, який повертає елементи колекції по одному.

foreach реалізований в Iterable через iterator.

def foreach[U](f: Elem => U): Unit = {
  val it = iterator
  while (it.hasNext) f(it.next())
}


Iterable наслідують Seq, Set, Map. Всі вони реалізують типаж PartialFunction з методами apply і isDefinedAt.

Для послідовностей Seq, apply - одержання елементу за індексом, починаючи з нуля. Наприклад, Seq(1, 2, 3)(0) == 1.

Для множин Set, apply - перевірка елемента на належність множині. Наприклад, Set('a', 'b', 'c')('a') == true, Set()('a') == false.

Для відображень Map, apply - вибір. Наприклад, Map('a' -> 1, 'b' -> 10, 'c' -> 100)('b') == 10.