开发者

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, deseria开发者_如何学编程lize the elements, and return a Seq.


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.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜