Scala for java list

Packages

Other packages exist. See the complete list on the right.

Additional parts of the standard library are shipped as separate libraries. These include:

  • scala.reflect — Scala’s reflection API (scala-reflect.jar)
  • scala.xml — XML parsing, manipulation, and serialization (scala-xml.jar)
  • scala.swing — A convenient wrapper around Java’s GUI framework called Swing (scala-swing.jar)
  • scala.util.parsing — Parser combinators , including an example implementation of a JSON parser (scala-parser-combinators.jar)

Automatic imports

Identifiers in the scala package and the scala.Predef object are always in scope by default.

Some of these identifiers are type aliases provided as shortcuts to commonly used classes. For example, List is an alias for scala.collection.immutable.List .

Other aliases refer to classes provided by the underlying platform. For example, on the JVM, String is an alias for java.lang.String .

Guide

A detailed guide for using the collections library is available at http://docs.scala-lang.org/overviews/collections/introduction.html. Developers looking to extend the collections library can find a description of its architecture at http://docs.scala-lang.org/overviews/core/architecture-of-scala-collections.html.

Using Collections

It is convenient to treat all collections as either a scala.collection.Traversable or scala.collection.Iterable, as these traits define the vast majority of operations on a collection. Collections can, of course, be treated as specifically as needed, and the library is designed to ensure that the methods that transform collections will return a collection of the same type:

scala> val array = Array(1,2,3,4,5,6) array: Array[Int] = Array(1, 2, 3, 4, 5, 6) scala> array map < _.toString >res0: Array[String] = Array(1, 2, 3, 4, 5, 6) scala> val list = List(1,2,3,4,5,6) list: List[Int] = List(1, 2, 3, 4, 5, 6) scala> list map < _.toString >res1: List[String] = List(1, 2, 3, 4, 5, 6)

Creating Collections

The most common way to create a collection is to use its companion object as a factory. The three most commonly used collections are scala.collection.Seq, scala.collection.immutable.Set, and scala.collection.immutable.Map. They can be used directly as shown below since their companion objects are all available as type aliases in either the scala package or in scala.Predef . New collections are created like this:

scala> val seq = Seq(1,2,3,4,1) seq: Seq[Int] = List(1, 2, 3, 4, 1) scala> val set = Set(1,2,3,4,1) set: scala.collection.immutable.Set[Int] = Set(1, 2, 3, 4) scala> val map = Map(1 -> "one", 2 -> "two", 3 -> "three", 2 -> "too") map: scala.collection.immutable.Map[Int,String] = Map(1 -> one, 2 -> too, 3 -> three)

It is also typical to prefer the scala.collection.immutable collections over those in scala.collection.mutable; the types aliased in the scala.Predef object are the immutable versions. Also note that the collections library was carefully designed to include several implementations of each of the three basic collection types. These implementations have specific performance characteristics which are described in the guide. The concrete parallel collections also have specific performance characteristics which are described in the parallel collections guide

Converting to and from Java Collections

The scala.collection.JavaConverters object provides a collection of decorators that allow converting between Scala and Java collections using asScala and asJava methods.

Читайте также:  Java получение данных ldap

Источник

Conversions Between Java and Scala Collections

Like Scala, Java also has a rich collections library. There are many similarities between the two. For instance, both libraries know iterators, iterables, sets, maps, and sequences. But there are also important differences. In particular, the Scala libraries put much more emphasis on immutable collections, and provide many more operations that transform a collection into a new one.

Sometimes you might need to pass from one collection framework to the other. For instance, you might want to access an existing Java collection as if it were a Scala collection. Or you might want to pass one of Scala’s collections to a Java method that expects its Java counterpart. It is quite easy to do this, because Scala offers implicit conversions between all the major collection types in the JavaConverters object. In particular, you will find bidirectional conversions between the following types.

Iterator java.util.Iterator Iterator java.util.Enumeration Iterable java.lang.Iterable Iterable java.util.Collection mutable.Buffer java.util.List mutable.Set java.util.Set mutable.Map java.util.Map mutable.ConcurrentMap java.util.concurrent.ConcurrentMap 

To enable these conversions, simply import them from the JavaConverters object:

scala> import collection.JavaConverters._ import collection.JavaConverters._ 

This enables conversions between Scala collections and their corresponding Java collections by way of extension methods called asScala and asJava :

scala> import collection.mutable._ import collection.mutable._ scala> val jul: java.util.List[Int] = ArrayBuffer(1, 2, 3).asJava jul: java.util.List[Int] = [1, 2, 3] scala> val buf: Seq[Int] = jul.asScala buf: scala.collection.mutable.Seq[Int] = ArrayBuffer(1, 2, 3) scala> val m: java.util.Map[String, Int] = HashMap("abc" -> 1, "hello" -> 2).asJava m: java.util.Map[String,Int] =

Internally, these conversions work by setting up a “wrapper” object that forwards all operations to the underlying collection object. So collections are never copied when converting between Java and Scala. An interesting property is that if you do a round-trip conversion from, say a Java type to its corresponding Scala type, and back to the same Java type, you end up with the identical collection object you have started with.

Certain other Scala collections can also be converted to Java, but do not have a conversion back to the original Scala type:

Seq => java.util.List mutable.Seq => java.util.List Set => java.util.Set Map => java.util.Map 

Because Java does not distinguish between mutable and immutable collections in their type, a conversion from, say, scala.immutable.List will yield a java.util.List , where all mutation operations throw an “UnsupportedOperationException”. Here’s an example:

scala> val jul = List(1, 2, 3).asJava jul: java.util.List[Int] = [1, 2, 3] scala> jul.add(7) java.lang.UnsupportedOperationException at java.util.AbstractList.add(AbstractList.java:148) 

Источник

Читайте также:  Python string null or empty

Преобразования между Java и Scala коллекциями

Как и в Scala, в Java есть богатая библиотека коллекций. Между ними много общего. Например, обе библиотеки предоставляют итераторы, итерируемые сущности, множества, мапы и списки. Но есть и серьезные различия. В частности, библиотека Scala фокусируют больше внимания на неизменяемых коллекциях, предоставляя больше возможностей для преобразования исходной коллекции в новую.

Иногда вам может понадобиться передать данные из одного фреймворка с коллекциями в другой. Например, вам может понадобиться доступ к существующей коллекции в Java, как если бы это была коллекция Scala. Или вы захотите передать одну из коллекций Scala методу в Java, который ожидает схожую коллекцию из Java. Сделать это довольно просто, потому что Scala предоставляет неявные преобразования всех основных типов коллекций используя CollectionConverters объект. В частности, вы найдете двухсторннее преобразование между следующими типами:

Iterator java.util.Iterator Iterator java.util.Enumeration Iterable java.lang.Iterable Iterable java.util.Collection mutable.Buffer java.util.List mutable.Set java.util.Set mutable.Map java.util.Map mutable.ConcurrentMap java.util.concurrent.ConcurrentMap 

Чтобы задействовать эти неявные преобразования, просто импортируйте объект CollectionConverters :

scala> import scala.jdk.CollectionConverters._ import scala.jdk.CollectionConverters._ 

Это позволит преобразовывать коллекции Scala в соответствующие коллекции Java с помощью методов расширения, называемых asScala и asJava :

scala> import collection.mutable._ import collection.mutable._ scala> val jul: java.util.List[Int] = ArrayBuffer(1, 2, 3).asJava jul: java.util.List[Int] = [1, 2, 3] scala> val buf: Seq[Int] = jul.asScala buf: scala.collection.mutable.Seq[Int] = ArrayBuffer(1, 2, 3) scala> val m: java.util.Map[String, Int] = HashMap("abc" -> 1, "hello" -> 2).asJava m: java.util.Map[String,Int] =

Внутри эти преобразования работают путем установки объекта “обертки”, который перенаправляет все операции на базовый объект коллекции. Таким образом, коллекции никогда не копируются при конвертировании между Java и Scala. Интересным свойством является то, что если вы выполняете преобразование из типа Java в соответствующий тип Scala и обратно в тот же тип Java, вы получаете идентичный объект коллекции, с которого начали.

Некоторые коллекции Scala могут быть преобразованы в Java, но не могут быть преобразованы обратно в исходный тип Scala:

Seq => java.util.List mutable.Seq => java.util.List Set => java.util.Set Map => java.util.Map 

Поскольку Java не различает изменяемые и неизменяемые коллекции по их типам, преобразование из, скажем, scala.immutable.List даст результат java.util.List , в котором любые операции преобразования кидают исключение “UnsupportedOperationException”. Вот пример:

scala> val jul = List(1, 2, 3).asJava jul: java.util.List[Int] = [1, 2, 3] scala> jul.add(7) java.lang.UnsupportedOperationException at java.util.AbstractList.add(AbstractList.java:148) 

Источник

Conversions Between Java and Scala Collections

Like Scala, Java also has a rich collections library. There are many similarities between the two. For instance, both libraries know iterators, iterables, sets, maps, and sequences. But there are also important differences. In particular, the Scala libraries put much more emphasis on immutable collections, and provide many more operations that transform a collection into a new one.

Читайте также:  Транслитерация php для url

Sometimes you might need to pass from one collection framework to the other. For instance, you might want to access an existing Java collection as if it were a Scala collection. Or you might want to pass one of Scala’s collections to a Java method that expects its Java counterpart. It is quite easy to do this, because Scala offers implicit conversions between all the major collection types in the CollectionConverters object. In particular, you will find bidirectional conversions between the following types.

Iterator java.util.Iterator Iterator java.util.Enumeration Iterable java.lang.Iterable Iterable java.util.Collection mutable.Buffer java.util.List mutable.Set java.util.Set mutable.Map java.util.Map mutable.ConcurrentMap java.util.concurrent.ConcurrentMap 

To enable these conversions, import them from the CollectionConverters object:

scala> import scala.jdk.CollectionConverters._ import scala.jdk.CollectionConverters._ 
scala> import scala.jdk.CollectionConverters.* import scala.jdk.CollectionConverters.* 

This enables conversions between Scala collections and their corresponding Java collections by way of extension methods called asScala and asJava :

scala> import collection.mutable._ import collection.mutable._ scala> val jul: java.util.List[Int] = ArrayBuffer(1, 2, 3).asJava val jul: java.util.List[Int] = [1, 2, 3] scala> val buf: Seq[Int] = jul.asScala val buf: scala.collection.mutable.Seq[Int] = ArrayBuffer(1, 2, 3) scala> val m: java.util.Map[String, Int] = HashMap("abc" -> 1, "hello" -> 2).asJava val m: java.util.Map[String,Int] = abc=1, hello=2> 
scala> import collection.mutable.* import collection.mutable.* scala> val jul: java.util.List[Int] = ArrayBuffer(1, 2, 3).asJava val jul: java.util.List[Int] = [1, 2, 3] scala> val buf: Seq[Int] = jul.asScala val buf: scala.collection.mutable.Seq[Int] = ArrayBuffer(1, 2, 3) scala> val m: java.util.Map[String, Int] = HashMap("abc" -> 1, "hello" -> 2).asJava val m: java.util.Map[String,Int] = abc=1, hello=2> 

Internally, these conversion work by setting up a “wrapper” object that forwards all operations to the underlying collection object. So collections are never copied when converting between Java and Scala. An interesting property is that if you do a round-trip conversion from, say a Java type to its corresponding Scala type, and back to the same Java type, you end up with the identical collection object you have started with.

Certain other Scala collections can also be converted to Java, but do not have a conversion back to the original Scala type:

Seq => java.util.List mutable.Seq => java.util.List Set => java.util.Set Map => java.util.Map 

Because Java does not distinguish between mutable and immutable collections in their type, a conversion from, say, scala.immutable.List will yield a java.util.List , where all mutation operations throw an “UnsupportedOperationException”. Here’s an example:

scala> val jul = List(1, 2, 3).asJava val jul: java.util.List[Int] = [1, 2, 3] scala> jul.add(7) java.lang.UnsupportedOperationException at java.util.AbstractList.add(AbstractList.java:148) 

Источник

Оцените статью