Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Java array to Scala collection

Tags:

java

scala

I would like to map over a Java array in Scala. For normal Java collections, I know I could use

import scala.collection.JavaConverters._

new java.util.ArrayList[Int](1).asScala.map(_.toString)

However, for an array this conversion doesn't work:

import scala.collection.JavaConverters._

java.util.Locale.getAvailableLocales.asScala // doesn't compile

So how do I convert a Java array to a Scala collection or iterable or something I can map on?

like image 984
Zoltán Avatar asked Aug 03 '16 12:08

Zoltán


People also ask

Can I use Java list in Scala?

A java list can be returned from a Scala program by writing a user defined method of Java in Scala. Here, we don't even need to import any Scala's JavaConversions object in order to make this conversions work. Now, lets see some examples.

What is SEQ in Scala?

Scala Seq is a trait to represent immutable sequences. This structure provides index based access and various utility methods to find elements, their occurences and subsequences. A Seq maintains the insertion order.

What is collections in Scala?

Scala has a rich set of collection library. Collections are containers of things. Those containers can be sequenced, linear sets of items like List, Tuple, Option, Map, etc. The collections may have an arbitrary number of elements or be bounded to zero or one element (e.g., Option).


2 Answers

You don't have to import any implicit conversion for the map to be available over Java arrays. Try running the following in Scala shell:

java.util.Locale.getAvailableLocales.map(_.toString)

The implicit conversion that allows the usage functions like map and filter over Java arrays comes with the Predef, which is imported implicitly.

As you mentioned in your own answer you can also explicitly convert an Array to another collection (which is possible thanks to the implicit conversion I mentioned previously).

like image 151
stefanobaghino Avatar answered Sep 29 '22 19:09

stefanobaghino


Aand I just found it:

Locale.getAvailableLocales.to[Seq]

No need for any implicit converters, or anything.

like image 28
Zoltán Avatar answered Sep 29 '22 19:09

Zoltán