我一直在寻找一些关于如何将ArrayBuffer
转换为Set
的时间,HashSet
我想是准确的。任何提示?
答案 0 :(得分:9)
toSet
个功能
示例:
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()
答案 1 :(得分:3)
设置:
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)
到HashSet:
scala> val hs = new HashSet[Int]++ bf.toSet
hs: scala.collection.immutable.HashSet[Int] = Set(1, 2, 3, 4)
答案 2 :(得分:2)
为了完整起见,还有一个方法:
scala> import collection.mutable.ArrayBuffer
import collection.mutable.ArrayBuffer
scala> val as = ArrayBuffer(34, 89, 11)
as: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(34, 89, 11)
scala> Set(as: _*)
res13: scala.collection.immutable.Set[Int] = Set(34, 89, 11)