Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iterating over Scala collections in Java

How I can iterate over Scala collections in Java?

like image 235
barroco Avatar asked Sep 05 '10 23:09

barroco


People also ask

Which expression is one way to iterate over a collection in Scala?

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.

Which expression is one way to iterate over a collection and generate a collection of each iteration's result?

forEach() method is available in Java 8 and each collection has this method that implements the iteration internally. Syntax used : With iterable variable.

Is Scala iterator lazy?

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.


1 Answers

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?

like image 177
Synesso Avatar answered Nov 11 '22 08:11

Synesso