Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert java.util.List[java.lang.Double] to Scala's List[Double]?

I'd like to convert a Java list of Java doubles (java.util.List[java.lang.Double]) to a Scala list of Scala doubles (List[Double]) in an efficient way.

Currently I'm mapping over the list converting each Double value to a Scala Double. I'd prefer not to map over every value and am looking for a more efficient way of doing this.

import collection.JavaConversions._
import collection.mutable.Buffer

val j: java.util.List[java.lang.Double] = Buffer(new java.lang.Double(1.0), new java.lang.Double(2.0))
val s: List[Double] = ...

I've seen documentation to go from Scala --> Java, but not much going the other way.

like image 233
Erik Shilts Avatar asked May 23 '14 05:05

Erik Shilts


1 Answers

The recommendation is to use JavaConverters, not JavaConversions:

import collection.JavaConverters._
import scala.collection.breakOut
val l: List[Double] = j.asScala.map(_.doubleValue)(breakOut)

doubleValue will convert it from a java.lang.Double into a scala.Double. breakOut tells it to produce a List as the result of the map, without having to traverse it another time to convert to a List. You could also just do toList instead of breakOut if you didn't care about the extra traversal.

The Java classes are entirely different objects from the Scala ones; it's not just a name-change. Thus, it would be impossible to convert without traversing. You have to create an entirely new collection and then look at each element in order to (convert it and) move it over.

The reason the types are different is that java.lang.Double is a "boxed primitive" whereas scala.Double is equivalent to Java's double primitive. The conversion here is essentially "unboxing" the primitive.

like image 116
dhg Avatar answered Oct 02 '22 14:10

dhg