10

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

new HashSet<T>(c)

where c is of type Collection<? extends T>?.

All I can find in the HashSet Object is apply.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
oxbow_lakes
  • 133,303
  • 56
  • 317
  • 449

3 Answers3

14

The most concise way to do this is probably to use the ++ operator:

import scala.collection.immutable.HashSet
val list = List(1,2,3)
val set = HashSet() ++ list
Fabian Steeg
  • 44,988
  • 7
  • 85
  • 112
8

There are two parts to the answer. The first part is that Scala variable argument methods that take a T* are a sugaring over methods taking Seq[T]. You tell Scala to treat a Seq[T] as a list of arguments instead of a single argument using "seq : _*".

The second part is converting a Collection[T] to a Seq[T]. There's no general built in way to do in Scala's standard libraries just yet, but one very easy (if not necessarily efficient) way to do it is by calling toArray. Here's 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)

Note the scala.Predef.Set and scala.collection.immutable.HashSet are synonyms.

James Iry
  • 19,367
  • 3
  • 64
  • 56
  • As it turns out I can't do this because my "inner" collection is actually an instance of java.util.List, not a Scala Seq. I've asked this question as a follow up: http://stackoverflow.com/questions/674713/converting-java-collection-into-scala-collection – oxbow_lakes Mar 23 '09 at 18:47
1

From Scala 2.13 use the companion object

import scala.collection.immutable.HashSet
val list = List(1,2,3)
val set = HashSet.from(list)
Nils
  • 11
  • 2