scala 如何将 Array[String] 转换为 Set[String]?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5778657/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 02:58:30  来源:igfitidea点击:

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

scalascala-collections

提问by dave4420

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.

我认为这是一个单一的方法调用,但我在 Scala 文档中找不到它。

I'm using scala 2.8.1.

我正在使用 Scala 2.8.1。

回答by tenshi

This method called toSet, e.g.:

此方法称为toSet,例如:

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 toSetmethod does not exist for the Array. But there is an implicit conversion to ArrayOps.

在这种情况下,toSet方法不存在Array。但是有一个到ArrayOps的隐式转换。

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

在这种情况下,我可以建议您查看Predef。通常你应该在那里找到一些合适的隐式转换。genericArrayOps在这种情况下将使用。genericWrapArray也可以使用,但优先级较低。

回答by missingfaktor

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)