开发者

How do I convert an Array[String] to a Set[String]?

I have an array of strings. What's the best way to turn it into an immutable set of strings?

I presume this is a single method call, but I can't find it in the scala docs.

I'm usin开发者_StackOverflowg scala 2.8.1.


This method called toSet, e.g.:

scala> val arr = Array("a", "b", "c")
arr: Array[java.lang.String] = Array(a, b, c)

scala> arr.toSet
res1: scala.collection.immutable.Set[java.lang.String] = Set(a, b, c)

In this case toSet method does not exist for the Array. But there is an implicit conversion to ArrayOps.

In such cases I can advise you to look in Predef. Normally you should find some suitable implicit conversion there. genericArrayOps would be used in this case. genericWrapArray also can be used, but it has lower priority.


scala> val a = Array("a", "b", "c")
a: Array[java.lang.String] = Array(a, b, c)

scala> Set(a: _*)
res0: scala.collection.immutable.Set[java.lang.String] = Set(a, b, c)

// OR    

scala> a.toSet
res1: scala.collection.immutable.Set[java.lang.String] = Set(a, b, c)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜