Is there any concise way to convert a Seq
into ArrayBuffer
in Scala?
Arrays -- An array is a data structure which stores a collection of elements of the same type. Arrays have a fixed size. ArrayBuffer -- An ArrayBuffer is very similar to an array, except it can grow in size after it has been initialized.
What is an ArrayBuffer? As per the Scala Documentation, an ArrayBuffer is a mutable data structure which allows you to access and modify elements at specific index. Compared to the previous tutorial on Array, an ArrayBuffer is resizable while an Array is fixed in size.
Scala Seq is a trait to represent immutable sequences. This structure provides index based access and various utility methods to find elements, their occurences and subsequences. A Seq maintains the insertion order.
Scala's default Seq class is mutable. Yes, you read that right. I think it's an extremely important thing to be aware of, and I'm not sure it's known widely enough.
scala> val seq = 1::2::3::Nil
seq: List[Int] = List(1, 2, 3)
scala> seq.toBuffer
res2: scala.collection.mutable.Buffer[Int] = ArrayBuffer(1, 2, 3)
EDIT After Scala 2.1x, there is a method .to[Coll]
defined in TraversableLike, which can be used as follow:
scala> import collection.mutable
import collection.mutable
scala> seq.to[mutable.ArrayBuffer]
res1: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1, 2, 3)
scala> seq.to[mutable.Set]
res2: scala.collection.mutable.Set[Int] = Set(1, 2, 3)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With