开发者

iterating over Scala collections in Java

How I can iterate over Scala collections in Jav开发者_JS百科a?


Some example Scala

class AThing {
  @scala.reflect.BeanProperty val aList = List(1,2,3,4,99)
}

A Java client

public class UseAThing {
  public static void main(String a[]) {
    AThing thing = new AThing();
    scala.collection.Iterator iter = thing.getAList().iterator();
    while (iter.hasNext()) {
      System.out.println(iter.next());
    }
  }
}

Output

jem@Respect:~/c/user/jem$ java -cp /opt/scala/lib/scala-library.jar:. UseAThing
1
2
3
4
99

Does that help?


Get a Scala Iterator from the collection and use a conversion from scala.collection.JavaConversions to turn it into a Java Iterator.

Here's an example:

scala> val li1 = List(2, 3, 5, 7, 11)
li1: List[Int] = List(2, 3, 5, 7, 11)

scala> val ii1 = li1.iterator
ii1: Iterator[Int] = non-empty iterator

scala> import collection.JavaConversions._
import collection.JavaConversions._

scala> val ji1: java.util.Iterator[Int] = ii1
ji1: java.util.Iterator[Int] = IteratorWrapper(non-empty iterator)

scala> val ji2 = ii1: java.util.Iterator[Int]
ji2: java.util.Iterator[Int] = IteratorWrapper(non-empty iterator)

With the JavaConversions imported into any given scope, there's an implicit conversion that will turn any Scala Iterator[T] into a corresponding Java Iterator<T>. In the preceding example, the explicit type of the ji1 declaration triggered the application of the implicit conversion of the initializer, ii1. In the ji2 case, the type ascription on ii1 triggers the conversion.


for(Item item: JavaConverters.seqAsJavaListConverter(seq).asJava()) {
    // Do thing with item
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜