Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scala: how to convert ArrayBuffer to a Set?

I've been looking for a bit of time on how to convert an ArrayBuffer to a Set, an HashSet I guess to be precise. Any hint?

like image 966
space borg Avatar asked Feb 01 '12 22:02

space borg


2 Answers

There is a toSet function implemented in ArrayBuffer

Example:

scala> import collection.mutable.ArrayBuffer
import collection.mutable.ArrayBuffer

scala> import collection.immutable.HashSet
import collection.immutable.HashSet

scala> val a = new ArrayBuffer(2)
a: scala.collection.mutable.ArrayBuffer[Nothing] = ArrayBuffer()

scala> val b = a.toSet
b: scala.collection.immutable.Set[Nothing] = Set()
like image 63
Christopher Chiche Avatar answered Sep 21 '22 19:09

Christopher Chiche


To Set:

scala> val bf = ArrayBuffer(1,2,3,4)
bf: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1, 2, 3, 4)
scala> bf.toSet
res0: scala.collection.immutable.Set[Int] = Set(1, 2, 3, 4)

To HashSet:

scala> val hs = new HashSet[Int]++ bf.toSet
hs: scala.collection.immutable.HashSet[Int] = Set(1, 2, 3, 4)
like image 43
om-nom-nom Avatar answered Sep 24 '22 19:09

om-nom-nom