trikk
trikk

Reputation: 67

How to convert a SortedSet in Java to a Seq in Scala

The Jedis call I'm using returns a Set, although at runtime it is actually a LinkedHashSet. I want to pull it into Scala, deserialize the elements, and return a Seq.

Upvotes: 1

Views: 781

Answers (2)

Kevin Wright
Kevin Wright

Reputation: 49705

Easy!

import collection.JavaConverters._
val theJavaSet = methodReturningLinkedHashSet()
theJavaSet.asScala.toSeq

I'd also tend to avoid JavaConversions (unless restricted by an older version of Scala). JavaConverters offers more control, and is immune from a couple of problems that can occur in more complicated scenarios.

Upvotes: 3

huynhjl
huynhjl

Reputation: 41646

Like Kevin says but without the typo, on 2.8.1 or later:

val javaSet: java.util.Set[String] = new java.util.LinkedHashSet[String]()
javaSet.add("a")
javaSet.add("b")
import collection.JavaConverters._
javaSet.asScala.toSeq
// res2: Seq[String] = ArrayBuffer(a, b)

or (also works on 2.8.0):

import collection.JavaConversions._
javaSet.toSeq

Upvotes: 0

Related Questions