Java – Scala is equivalent to the new HashSet (Collection)

What is the equivalent Scala constructor (to create immutable hashsets) to Java

new HashSet<T>(c)

Where C is collection < extended T > I can find everything in the HashSet object

Solution

The answer has two parts The first part is the scala variable parameter method using t *, which uses SEQ [t] You tell Scala to use SEQ [t] as a parameter list instead of using "SEQ: *" as a single parameter

The second part is to convert the set [t] to SEQ [t] There are no general built-in methods in scala's standard library, but a very simple (if not effective) method is to call toArray This is a complete example

scala> val lst : java.util.Collection[String] = new java.util.ArrayList
lst: java.util.Collection[String] = []

scala> lst add "hello"
res0: Boolean = true

scala> lst add "world"
res1: Boolean = true

scala> Set(lst.toArray : _*)
res2: scala.collection.immutable.Set[java.lang.Object] = Set(hello,world)

Pay attention to scala Predef. Set and scala collection. immutable. HashSet is a synonym

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>