Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

comparing Scala lists with Java lists

How can I compare a Scala list with a Java list?

scala> List(1, 2, 3, 4, 5)
res0: List[Int] = List(1, 2, 3, 4, 5)

scala> java.util.Arrays.asList(1, 2, 3, 4, 5)
res1: java.util.List[Int] = [1, 2, 3, 4, 5]

scala> res0 == res1
res2: Boolean = false

Is there some static helper method for comparison that accepts both Scala lists and Java lists? Or is there a kind of "lazy wrapper" over both sorts of lists which I can then directly compare via ==?

like image 368
fredoverflow Avatar asked Apr 12 '12 06:04

fredoverflow


2 Answers

... or use sameElements.

scala> import collection.JavaConversions._
import collection.JavaConversions._

scala> res0.sameElements(res1)            
res3: Boolean = true
like image 144
Wilfred Springer Avatar answered Nov 17 '22 19:11

Wilfred Springer


You can use JavaConverters for this:

scala> import collection.JavaConverters._
import collection.JavaConverters._

scala> res0 == res1.asScala
res2: Boolean = true

Note that the asScala only returns a view on the original List, see documentation of asScalaBufferConverter in JavaConverters documentation.

like image 24
robinst Avatar answered Nov 17 '22 21:11

robinst