Convert Scala Set into Java (java.util.Set)?
Asked Answered
M

5

28

I have a Set in Scala (I can choose any implementation as I am creating the Set. The Java library I am using is expecting a java.util.Set[String].

Is the following the correct way to do this in Scala (using scala.collection.jcl.HashSet#underlying):

import com.javalibrary.Animals

var classes = new scala.collection.jcl.HashSet[String]
classes += "Amphibian"
classes += "Reptile"
Animals.find(classes.underlying)

It seems to be working, but since I am very new to Scala I want to know if this is the preferred way (any other way I try I am getting a type-mismatch error):

error: type mismatch;
 found   : scala.collection.jcl.HashSet[String]
 required: java.util.Set[_]
Mortification answered 10/2, 2010 at 0:32 Comment(0)
C
24

If you were asking about Scala 2.8, Java collections interoperability is supplied by scala.collection.JavaConversions. In this case, you want JavaConversions.asSet(...) (there's one for each direction, Java -> Scala and Scala -> Java).

For Scala 2.7, each scala.collection.jcl class that wraps a Java collection has an underlying property which provides the wrapped Java collection instance.

Confucius answered 10/2, 2010 at 2:27 Comment(0)
L
10

Since Scala 2.12.0 scala.collection.JavaConversions is deprecated:

Therefore, this API has been deprecated and JavaConverters should be used instead. JavaConverters provides the same conversions, but through extension methods.

And since Scala 2.8.1 you can use scala.collection.JavaConverters for this purpose:

import scala.collection.JavaConverters._
val javaSet = new java.util.HashSet[String]()
val scalaSet = javaSet.asScala
val javaSetAgain = scalaSet.asJava
Lisettelisha answered 27/11, 2016 at 13:17 Comment(1)
And for 2.13 JavaConverters have been deprecated.Junia
D
7

Note that starting Scala 2.13, package scala.jdk.CollectionConverters replaces deprecated packages scala.collection.JavaConverters/JavaConversions._:

import scala.jdk.CollectionConverters._

// val scalaSet: Set[String] = Set("a", "b")
val javaSet = scalaSet.asJava
// javaSet: java.util.Set[String] = [a, b]
javaSet.asScala
// scala.collection.mutable.Set[String] = Set(a, b)
Deathday answered 29/3, 2019 at 21:14 Comment(0)
E
5

For 2.7.x I highly recommend using: http://github.com/jorgeortiz85/scala-javautils

Eschew answered 10/2, 2010 at 10:18 Comment(0)
M
4

In Scala 2.12 it is possible to use : scala.collection.JavaConverters.setAsJavaSet(scalaSetInstance)

Moselle answered 28/8, 2017 at 11:58 Comment(1)
Thank you, I was looking for the way to do it from within Java code + this fits the billHorsepowerhour

© 2022 - 2024 — McMap. All rights reserved.