Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to iterate Java List in Scala

I'm using the Java Twitter4J library in a Scala project.

I'm calling the method

twitter.getFriendsStatuses()

This method returns a list of twitter4j.User objects containing statuses.

I try to iterate over them and it goes in an infinite loop over the first element:

val users:List[User] = twitter.getFriendsStatuses(userId, paging.getSinceId())
while( users.iterator.hasNext() ) {
  println(users.iterator.next().getStatus())
}

Any ideas?

like image 943
Sri Avatar asked Mar 14 '11 13:03

Sri


2 Answers

I guess users.iterator produces the new iterator each time it's evaluated. Try this:

val it = users.iterator
while(it.hasNext() ) {
   println(it.next().getStatus())
}
like image 109
axtavt Avatar answered Nov 15 '22 08:11

axtavt


If you use Scala 2.8, you could use JavaConversion to convert Java collection to Scala collection automatically.

Ex.

import scala.collection.JavaConversions._

// Java Collection
val arrayList = new java.util.ArrayList[Int]
arrayList.add(2)
arrayList.add(3)
arrayList.add(4)

// It will implicitly covert to Scala collection, 
// so you could use map/foreach...etc.
arrayList.map(_ * 2).foreach(println)
like image 18
Brian Hsu Avatar answered Nov 15 '22 08:11

Brian Hsu