How I can iterate over Scala collections in Java?
A simple for loop that iterates over a collection is translated to a foreach method call on the collection. A for loop with a guard (see Recipe 3.3) is translated to a sequence of a withFilter method call on the collection followed by a foreach call.
forEach() method is available in Java 8 and each collection has this method that implements the iteration internally. Syntax used : With iterable variable.
Unlike operations directly on a concrete collection like List , operations on Iterator are lazy. A lazy operation does not immediately compute all of its results.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With