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

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

I am currently browsing the list, converting each double value to Scala Double. I would prefer not to match each value, and I'm looking for a more efficient way to do 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 saw the documentation starting with Scala -> Java, but not like otherwise.

+6
source share
2 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 converts it from a java.lang.Double to scala.Double . breakOut reports that it creates a List as a result of the map , without going any other time to convert it to a List . You can also just do toList instead of breakOut if you don't need an extra workaround.

Java classes are completely different objects from Scala; it's not just a name change. Thus, it would be impossible to convert without going through. You need to create a completely new collection, and then look at each item to (transform it and) move it.

The reason these types are different is because java.lang.Double is a "boxed primitive", whereas scala.Double is equivalent to a double Java primitive. The transformation here is essentially the "unboxing" of the primitive.

+15
source
 import collection.JavaConverters._ val javaList : java.util.List[Double] = ... val scalaList : List[Double] = j.asScala.toList 
0
source

Source: https://habr.com/ru/post/969729/


All Articles