Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Seq to ArrayBuffer

Is there any concise way to convert a Seq into ArrayBuffer in Scala?

like image 343
classicalist Avatar asked Sep 26 '11 09:09

classicalist


People also ask

What is the difference between Array and 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 ArrayBuffer in Scala?

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.

What is a SEQ in Scala?

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.

Is sequence mutable Scala?

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.


1 Answers

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)
like image 158
Eastsun Avatar answered Sep 20 '22 08:09

Eastsun