Samstag, 20. Februar 2010

How to transform a List into a java.util.List



implicit def toJavaList[A](i: scala.Iterable[A]): java.util.List[A] = {
val result = new java.util.ArrayList[A]
i.foreach(result.add)
java.util.Collections.unmodifiableList[A](result)
}


Or, if you don't need a immutable List:


implicit def toJavaMutableList[A](i: scala.Iterable[A]): java.util.List[A] = {
val result = new java.util.ArrayList[A]
i.foreach(result.add)
result
}



Example using javaMutableList :



val names = List("1","2","3","4","5","6","7")

val jlist: java.util.List[String] = names
jlist: java.util.List[String] = [1, 2, 3, 4, 5, 6, 7]

val shuffled = java.util.Collections.shuffle(jlist)
shuffled: Unit = ()

println(jlist)
[4, 5, 3, 7, 2, 6, 1]

Keine Kommentare:

Kommentar veröffentlichen