Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

More collections


May 14, 2021 Scala


Table of contents


More collections

Scala provides a good set of collection implementations, providing abstractions for some collection types. This allows your code to interact with Foo's collection without worrying about whether it's a List, a Set, or whatever type you have.

Here provides a good page to view the default implementations of the various collections and link to their scala online documentation.

Basics

Table List

Standard list.

scala> List(1, 2, 3)
res0: List[Int] = List(1, 2, 3)

You can connect them in a functional language.

scala> 1 :: 2 :: 3 :: Nil
res1: List[Int] = List(1, 2, 3)

Refer to the API documentation

Set Set

The set is not repeated

scala> Set(1, 1, 2)
res2: scala.collection.immutable.Set[Int] = Set(1, 2)

Refer to the API documentation

Sequence Seq

The sequence has a given order.

scala> Seq(1, 1, 2)
res3: Seq[Int] = List(1, 1, 2)

(Note that a list is returned.) B ecause Seq is a trait, and lists are a good implementation of sequences. A s you can see, Seq is also a factory singleton object that can be used to create lists.

Refer to the API documentation

Map map

A map is a key-value container.

scala> Map('a' -> 1, 'b' -> 2)
res4: scala.collection.immutable.Map[Char,Int] = Map((a,1), (b,2))

Refer to the API documentation

The hierarchy

The following are all qualities that have specific implementations in both mutable and immutable packages.

Traversable

All collections can be traversed. T his trait defines a standard function combination. These combinations are written based on foreach, and all collections must be implemented.

Refer to the API documentation

Iterable

The iterator() method returns an Iterator to iterate elements.

Refer to the API documentation

Seq sequence

A sequence of objects in order.

Refer to the API documentation

Set set

There is no duplicate collection of objects.

Refer to the API documentation

Map

Key value pair.

Refer to the API documentation

Method

Traversable

All of the following methods are available in subsyses. The types of arguments and returned values may look different because of the overlay of the sub-classes.

def head : A
def tail : Traversable[A]

This is where the function combination sub-definitions are.

def map [B] (f: (A) => B) : CC[B]

Returns a collection of each element that has been converted by f

def foreach[U](f: Elem => U): Unit

Perform f on each element in the collection.

def find (p: (A) => Boolean) : Option[A]

Returns the first element of the matching predicate function

def filter (p: (A) => Boolean) : Traversable[A]

Returns a collection of elements that match the predicate function

Divided:

def partition (p: (A) ⇒ Boolean) : (Traversable[A], Traversable[A])

Divide a collection into two parts according to the predicate function

def groupBy [K] (f: (A) => K) : Map[K, Traversable[A]]

Transformation:

Interestingly, you can convert collection types.

def toArray : Array[A]
def toArray [B >: A] (implicit arg0: ClassManifest[B]) : Array[B]
def toBuffer [B >: A] : Buffer[B]
def toIndexedSeq [B >: A] : IndexedSeq[B]
def toIterable : Iterable[A]
def toIterator : Iterator[A]
def toList : List[A]
def toMap [T, U] (implicit ev: <:<[A, (T, U)]) : Map[T, U]
def toSeq : Seq[A]
def toSet [B >: A] : Set[B]
def toStream : Stream[A]
def toString () : String
def toTraversable : Traversable[A]

Convert the map to an array, and you get an array of key-value pairs.

scala> Map(1 -> 2).toArray
res41: Array[(Int, Int)] = Array((1,2))

Iterable

Add access to an iterator.

  def iterator: Iterator[A]

What can an iterator provide you with?

def hasNext(): Boolean
def next(): A

This is very Javanial. You don't usually see iterators used in Scala, and it's usually more likely to appear with function combiners or for loops.

Set

  def contains(key: A): Boolean
  def +(elem: A): Set[A]
  def -(elem: A): Set[A]

Map

The sequence of key value pairs that are found by keys.

You can pass a key value to the list like this to apply()

scala> Map("a" -> 1, "b" -> 2)
res0: scala.collection.immutable.Map[java.lang.String,Int] = Map((a,1), (b,2))

Or something like this:

scala> Map(("a", 2), ("b", 2))
res0: scala.collection.immutable.Map[java.lang.String,Int] = Map((a,2), (b,2))

Off-topic

What ->? This is not a special syntax, this is a way to return a metagroup.

scala> "a" -> 2

res0: (java.lang.String, Int) = (a,2)

Keep in mind that this is just the syntax sugar of the following code

scala> "a".->(2)

res1: (java.lang.String, Int) = (a,2)

You can ++ the operator

scala> Map.empty ++ List(("a", 1), ("b", 2), ("c", 3))
res0: scala.collection.immutable.Map[java.lang.String,Int] = Map((a,1), (b,2), (c,3))

A common sub-class

Quick lookups of HashSet and HashMap, the most common forms of these collections. HashSet API , HashMap API

TreeMap is a sub-class of SortedMap that gives you orderly access. [ TreeMap API] ()

Vector is quickly randomly selected and updated quickly. Vector API

scala> IndexedSeq(1, 2, 3)
res0: IndexedSeq[Int] = Vector(1, 2, 3)

Int ordered sequence of intervals such as Range. Y ou'll often see it in the for loop. Range API

scala> for (i <- 1 to 3) { println(i) }
1
2
3

Ranges supports standard function combinations.

scala> (1 to 3).map { i => i }
res0: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 2, 3)

The default implementation

Using the trait's apply method gives you an instance of the default implementation, for example, Iterable (1, 2) returns a list as its default implementation.

scala> Iterable(1, 2)

res0: Iterable[Int] = List(1, 2)

The same is true of sequence Seq, as we saw earlier

scala> Seq(1, 2)
res3: Seq[Int] = List(1, 2)

scala> Iterable(1, 2)
res1: Iterable[Int] = List(1, 2)

scala> Sequence(1, 2)
warning: there were deprecation warnings; re-run with -deprecation for details
res2: Seq[Int] = List(1, 2)

Set

scala> Set(1, 2)
res31: scala.collection.immutable.Set[Int] = Set(1, 2)

Some descriptive traits

IndexedSeq provides quick random access to elements and a quick length operation. API Documentation: Http://www.scala-lang.org/api/current/scala/collection/IndexedSeq.html

LinearSeq provides quick access to the first element via head, as well as a quick tail operation. API documentation

Variable vs Immeda

Immedible

Advantages

  • Does not change in multithreaded

Disadvantages

  • Nothing can change

Scala allows us to be pragmatic, it encourages indignity, but does not punish the variability we need. T his is very similar to var vs. val. We always start with val and fall back to var if necessary.

We're in favor of using immedible versions of the collection, but you can switch to variable if performance makes it possible. Using immedible collections means that you don't accidentally change things in multiple threads.

Variable collection

All the classes discussed earlier are imm changeable. Let's discuss commonly used variable collections.

HashMap getOrElseUpdate += HashMap API

scala> val numbers = collection.mutable.Map(1 -> 2)
numbers: scala.collection.mutable.Map[Int,Int] = Map((1,2))

scala> numbers.get(1)
res0: Option[Int] = Some(2)

scala> numbers.getOrElseUpdate(2, 3)
res54: Int = 3

scala> numbers
res55: scala.collection.mutable.Map[Int,Int] = Map((2,3), (1,2))

scala> numbers += (4 -> 1)
res56: numbers.type = Map((2,3), (4,1), (1,2))

Live with Java

You can easily convert between Java and Scala's collection types with the JavaConverters package. It decorates commonly used Java collections with asScala and Scala collections with asJava methods.

   import scala.collection.JavaConverters._
   val sl = new scala.collection.mutable.ListBuffer[Int]
   val jl : java.util.List[Int] = sl.asJava
   val sl2 : scala.collection.mutable.Buffer[Int] = jl.asScala
   assert(sl eq sl2)

Two-way conversion:

scala.collection.Iterable <=> java.lang.Iterable
scala.collection.Iterable <=> java.util.Collection
scala.collection.Iterator <=> java.util.{ Iterator, Enumeration }
scala.collection.mutable.Buffer <=> java.util.List
scala.collection.mutable.Set <=> java.util.Set
scala.collection.mutable.Map <=> java.util.{ Map, Dictionary }
scala.collection.mutable.ConcurrentMap <=> java.util.concurrent.ConcurrentMap

The following one-way conversions are also available

scala.collection.Seq => java.util.List
scala.collection.mutable.Seq => java.util.List
scala.collection.Set => java.util.Set
scala.collection.Map => java.util.Map