Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
scala

How to do Scala Conversions between Java and Scala collections

Sarvech Qadir

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.

  1. Using the asScalaBuffer() method.
  2. Using the asScala method.
object Main extends App {
  // import relevant libraries
  import collection.JavaConverters._
  import collection.mutable._

  // method 1
  println("Method 1: ")
  val jList = java.util.Arrays.asList(1, 2, 3)
  println(jList)
  // using asScalaBuffer method
  val sBuffer = asScalaBuffer(jList)
  // Now since we have a scala buffer, we can use foreach
  // if you use foreach with Java oject, it will raise error
  sBuffer.foreach(println)

  println("Method 2: ")
  // method 2
  // Initalise Java Array
  val jul = ArrayBuffer(1, 2, 3).asJava
  // using .asScala method
  val buf = jul.asScala
  println(jul)
  buf.foreach(println)


}

RELATED TAGS

java
scala

CONTRIBUTOR

Sarvech Qadir
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring