Scala convert List[Int] to a java.util.List[java.lang.Integer]

Viewed 16518

Is there a way in Scala to convert a List[Int] to java.util.List[java.lang.Integer]?

I'm interfacing with Java (Thrift).

JavaConversions supports List --> java.util.List, and implicits exist between Int --> java.lang.Integer, but from what I can tell I would still need an extra pass to manually do the conversion:

val y = List(1)     
val z: java.util.List[Integer] = asList(y)  map { (x: Int) => x : java.lang.Integer }
6 Answers

Starting Scala 2.13, the standard library includes scala.jdk.CollectionConverters which provides Scala to Java implicit collection conversions.

Which we can combine with java.lang.Integer::valueOf to convert Scala's Int to Java's Integer:

import scala.jdk.CollectionConverters._

List(1, 2, 3).map(Integer.valueOf).asJava
// java.util.List[Integer] = [1, 2, 3]

I was trying to pass a Map[String, Double] to a Java method. But the problem was JavaConversions converts the Map to a java Map, but leaves the scala Double as is, instead of converting it to java.lang.Double. After a few hours of seaching I found [Alvaro Carrasco's answer])https://stackoverflow.com/a/40683561/1612432), it is as simple as doing:

val scalaMap = // Some Map[String, Double]
val javaMap = scalaMap.mapValues(Double.box)

After this, javaMap is a Map[String, java.lang.Double]. Then you can pass this to a java function that expects a Map<String, Double> and thanks to implicit conversions the Scala Map will be converted to java.util.Map

In your case would be the same, but with Int.box:

val y = List(1)
val javay = y.map(Int.box)
Related