Java与Scala集合互转
使用 scala.collection.JavaConverters 与Java集合交互。它有一系列的隐式转换,添加了asJava和asScala的转换方法。
import scala.collection.JavaConverters._
val list: java.util.List[Int] = List(1,2,3,4).asJava
val buffer: scala.collection.mutable.Buffer[Int] = list.asScala
以下集合可以进行任意,转换。但在某些情况下引入的隐式转换不正确或未引入,仍然无法进行正确转换,如API的例子
scala.collection.Iterable <=> java.lang.Iterable
scala.collection.Iterable <=> java.util.Collection
scala.collection.Iterator <=> java.util.{ Iterator, Enumeration }
scala.collection.mutable.Buffer <=> java.util.List
scala.collection.mutable.Set <=> java.util.Set
scala.collection.mutable.Map <=> java.util.{ Map, Dictionary }
scala.collection.concurrent.Map <=> java.util.concurrent.ConcurrentMap
总结下来就是:collection:可以指定元素排序规则:sort方法或继承comparable
scala.collection.Iterable<=>java.lang.{iterable,collection}
scala.collection.Iterator<=>java.util.{Iterator,Enumeration}
scala的Buffer对应就是java.util.List,不可直接使用,使用ListBuffer
scala.collection.mutable.Buffer<=>java.util.List
scala.collection.mutable.Set<=>java.util.Set
scala.collection.mutable.Map<=>java.util.{Map,Dictionary}
并发安全集合
scala.collection.concurrent.Map<=>java.util.concurrent.ConcurrentMap
以下为scala.collection.mutable.ListBuffer<=>java.util.List
除要求引入相应的转换类JavaConversions._,还有引入ListBuffer=>java.util.List 具体转换方法
- List 转 Seq:
List<String> tmpList = new ArrayList<>();
tmpList.add("abc");
Seq<String> tmpSeq = JavaConverters.asScalaIteratorConverter(tmpList.iterator()).asScala().toSeq();
- Seq 转 List:
List<String> tmpList = scala.collection.JavaConversions.seqAsJavaList(tmpSeq);