Facundo Ch.
Facundo Ch.

Reputation: 12234

How iterate a Groovy List with Java?

I have the following Groovy domain class:

class A {

  def lotOfBs = []

}

Now, from a Java class I need to iterate that array. These solutions did not work:

for ( B b : a.getLotOfBs() ){
  //COMPILATION ERROR
}

for ( int i = 0 ; i < a.getLotOfBs().length ; i++ ){
  //LENGTH ATTRIBUTE DOES NOT EXIST OR IT IS NOT VISIBLE
}

for ( int i = 0 ; i < a.getLotOfBs().size() ; i++ ){
  //SIZE METHOD DOES NOT EXIST
}

Do you have any suggestions?

Thanks in advance

Upvotes: 0

Views: 1078

Answers (1)

Anton Arhipov
Anton Arhipov

Reputation: 6591

The array in groovy class is an instance of java.util.ArrayList, so casting to Collection<T> should work:

  Collection<B> bs = (Collection<B>) a.getLotOfBs();

  for (B b : bs) {
    ...
  }

Upvotes: 2

Related Questions