Approach to go To and From Java Collections in Scala

JavaConverters and JavaConverters._ imports from Scala’s fashionable library can be used to make Java collections and Scala collections paintings together. Without the want to create boilerplate conversion code, those converters provide smooth conversion amongst Java and Scala collections.

Example 1: Below is the Scala program to transform a Java ArrayList with strings and a Java HashMap with string keys and integer values into Scala collections:

Scala
import scala.collection.JavaConverters._

// Java List to Scala List
val javaList = new java.util.ArrayList[String]()
javaList.add("Java")
javaList.add("Collections")
val scalaList = javaList.asScala
println(scalaList) 

// Java Map to Scala Map
val javaMap = new java.util.HashMap[String, Int]()
javaMap.put("one", 1)
javaMap.put("two", 2)
val scalaMap = javaMap.asScala
println(scalaMap) 

Output:

Java Collections to Scala Collections

Example 2: Below is the Scala program to convert Scala collections to Java collections:

Scala
import scala.collection.JavaConverters._

// Scala List to Java List
val scalaList = List("Scala", "Collections")
val javaList = scalaList.asJava
println(javaList) 

// Scala Map to Java Map
val scalaMap = Map("one" -> 1, "two" -> 2)
val javaMap = scalaMap.asJava
println(javaMap) 

Output:

Example 3: Below is the Scala program to convert Java list to Scala list and Scala map to Java map:

Scala
import scala.collection.JavaConverters._

// Convert Java List to Scala List
val javaList = new java.util.ArrayList[String]()
javaList.add("Java")
javaList.add("Collections")
val scalaList = asScalaBufferConverter(javaList).asScala.toList
println(scalaList) 

// Convert Scala Map to Java Map
val scalaMap = Map("one" -> 1, "two" -> 2)
val javaMap = mapAsJavaMapConverter(scalaMap).asJava
println(javaMap)

Output:


Conclusion:


The JavaConverters adapter will be used in the Scala code to convert the Java collection type to the same Scala collection type.



How to go To and From Java Collections in Scala?

In their respective languages, Java collections and Scala collections are two distinct sets of data structures that might be frequently utilized. Although Java collections are a factor of the Java Standard Library, Scala collections are made expressly to combine with the useful programming features of Scala.

You may also want to deal with Java collections from Scala and vice versa in lots of projects, especially people with mixed Java and Scala codebases. This article focuses on discussing how to go to and from Java Collections in Scala.

Similar Reads

Approach to go To and From Java Collections in Scala

JavaConverters and JavaConverters._ imports from Scala’s fashionable library can be used to make Java collections and Scala collections paintings together. Without the want to create boilerplate conversion code, those converters provide smooth conversion amongst Java and Scala collections....