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

旧时模样 提交于 2019-12-21 03:12:31

问题


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 using scala 2.8.1.


回答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.




回答2:


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)


来源:https://stackoverflow.com/questions/5778657/how-do-i-convert-an-arraystring-to-a-setstring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!