Convert java.util.Set to scala.collection.Set
Asked Answered
G

3

26

How can I convert a java.util.Set[String] to a scala.collection.Set with a generic type in Scala 2.8.1?

import scala.collection.JavaConversions._

var in : java.util.Set[String] = new java.util.HashSet[String]()

in.add("Oscar")
in.add("Hugo")

val out : scala.collection.immutable.Set[String] = Set(in.toArray : _*)

And this is the error message

<console>:9: error: type mismatch;  
found   : Array[java.lang.Object]
required: Array[_ <: String]   
val out : scala.collection.immutable.Set[String] = Set(javaset.toArray : _*)

What am I doing wrong?

Gottwald answered 26/5, 2011 at 19:6 Comment(0)
S
16

toArray() called on a java Set will return an array of Object. Since you already imported JavaConversions, asScalaSet will implicitly convert your Java set to a mutable Scala set or use toSet to convert it to an immutable set.

See also Convert Scala Set into Java (java.util.Set)

Schaller answered 26/5, 2011 at 19:35 Comment(2)
I read them, but the function asSet doesn't work. With toSet is works fine. Thank you very much.Gottwald
FYI JavaConversions is deprecated as of Scala 2.12.0. Use JavaConverters.Aviles
S
26

Use JavaConverters instead

import scala.collection.JavaConverters._

val out = in.asScala

out: scala.collection.mutable.Set[String] = Set(Hugo, Oscar)
Salami answered 26/5, 2011 at 19:34 Comment(3)
Oddly, but this import statement fails: import scala.collection.JavaConverters._ I use Scala version 2.8.1Gottwald
JavaConverters is avaliable Since 2.8.1Salami
this gives scala.collection.mutable.Set and I need scala.collection.immutable.SetGalvanism
S
16

toArray() called on a java Set will return an array of Object. Since you already imported JavaConversions, asScalaSet will implicitly convert your Java set to a mutable Scala set or use toSet to convert it to an immutable set.

See also Convert Scala Set into Java (java.util.Set)

Schaller answered 26/5, 2011 at 19:35 Comment(2)
I read them, but the function asSet doesn't work. With toSet is works fine. Thank you very much.Gottwald
FYI JavaConversions is deprecated as of Scala 2.12.0. Use JavaConverters.Aviles
C
0

That's an outdated answer. One needs to import

import scala.jdk.CollectionConverters.*

as shown in https://docs.scala-lang.org/overviews/collections-2.13/conversions-between-java-and-scala-collections.html

and then use .asScala or .asJava method based on the target collection type.

Champ answered 22/11, 2023 at 11:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.