How to do Scala Conversions between Java and Scala collections
Scala and Java both have a large amount of collections libraries. While there are several similarities between Scala and Java libraries, they also have several differences. The major difference between the two is the fact that Scala libraries place more emphasis on immutable collections.
For many programmers, once they become associated and fluent in Scala methods such as foreach, map, iterators, and sets, they may want to treat Java collections as Scala collections. There are a few ways for a programmer to convert from one collection framework to another. The best way to do this is to use the methods of the JavaConversions object.
Possible Conversions
The following are the bidirectional conversions between Java and Scala frameworks.
Java | Scala |
Iterator | java.util.Iterator java.util.Enumeration |
Iterable | java.util.Enumeration java.util.Collection |
mutable.Buffer mutable.Set mutable.Map mutable.ConcurrentMap | java.util.List java.util.Set java.util.Map java.util.concurrent.ConcurrentMap |
Code
Let’s look at two ways to convert Array collections to buffer collections.
- Using the
asScalaBuffer()method. - Using the
asScalamethod.
object Main extends App {// import relevant librariesimport collection.JavaConverters._import collection.mutable._// method 1println("Method 1: ")val jList = java.util.Arrays.asList(1, 2, 3)println(jList)// using asScalaBuffer methodval sBuffer = asScalaBuffer(jList)// Now since we have a scala buffer, we can use foreach// if you use foreach with Java oject, it will raise errorsBuffer.foreach(println)println("Method 2: ")// method 2// Initalise Java Arrayval jul = ArrayBuffer(1, 2, 3).asJava// using .asScala methodval buf = jul.asScalaprintln(jul)buf.foreach(println)}
Free Resources