简体   繁体   中英

Converting a java.util.Set to java.util.List in Scala

While in a project that is a mix of Scala and Java, I need to convert a Java Set into a Java List while in the Scala portion of the code.

What are some efficient ways of doing this? I could potentially use JavaConverters to convert Java Set -> Scala Set -> Scala List -> Java List. Are there other options that would be more efficient?

Thanks

The Java collection classes provide a constructor that takes a Collection , so why not just use that?

def js2jl[A](s: java.util.Set[A]): java.util.List[A] = new java.util.ArrayList(s)

Nothing Scala-specific beyond the syntax, but that's not a bad thing in this case.

Why don't you do it just as you would in pure Java ? For example :

val mySet : java.util.Set[Integer] = new java.util.HashSet()
mySet.add(5)
val myList : java.util.List[Integer] = new java.util.ArrayList(mySet)
println(myList)

Is that what you want to do ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM