Convert Scala buffer to Java ArrayList

In my Scala function, I look at the Java ArrayCollection, retrieving specific elements that should form a new collection. In the end, it should be a Java-ArrayList again, because I'm interacting with the Java Framework. My code is:

// to make scala-style iterating over arraylist possible import scala.collection.JavaConversions._ // ArrayList contains elements of this type: class Subscription(val subscriber:User, val sender:User) // I'm getting this list from Java: val jArrayList = new ArrayList[Subscription] // Buffer:scala.collection.mutable.Buffer[User] val buffer = for (val subscription <- jArrayList ) yield subscription.sender 

How to convert a buffer to ArrayList [User]? Or should I not use income here?

+7
java scala
source share
3 answers

You should be able to convert it back by indicating what type you would like buffer be ( JavaConversions should be introduced into the game automatically when the type you are trying to get and the one you have is incompatible):

 val buffer: java.util.List[User] = for (val subscription <- jArrayList ) yield subscription.sender 

Alternatively, you can explicitly call the conversion from JavaConversions if you want to clearly indicate what you are doing:

 val buffer = asList( for ( ... ) ) // buffer should have type "java.util.List[User]" 

None of them actually produce an ArrayList ; rather, they create a common List , but usually the bad practice is to directly specify collection types. If you must have an ArrayList , pass List to the ArrayList constructor, which accepts Collection :

 new ArrayList( buffer ) 
+7
source share

You can pass a buffer in the ArrayList constructor to create a new java ArrayList:

 var newArray = new ArrayList[Int] (buffer) 
+2
source share

When used for understanding, the base code uses map , flatMap , foreach , filter or withFilter - see related questions. In this particular example, this code will be equivalent to jArrayList.map(_.sender) , and map create new collections (I ignore the implicit conversion here to make it simple).

What is happening here is perhaps unintuitive, and perhaps one can improve, is that ArrayList does not implement map . An implicit conversion gives instead a Buffer , and a map on Buffer returns a Buffer .

Of course, Buffer on JavaConversions saves the base collection, ArrayList , as a backup storage. On the other hand, the created Buffer will not be based on this, but in one of Scala's own collections.

You can always do this:

 val buffer = (for (val subscription <- jArrayList ) yield subscription.sender).asList 
+1
source share

All Articles