Unable to iterate Java List in Scala
I'm using the Java Twitter4J library in a Scala project.
I'm calling the method
twitter.开发者_JS百科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?
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())
}
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)
What's wrong with just
users.foreach(user => println(user.getStatus()))
or even
users.map(_.getStatus()).foreach(println _)
or, if you're worried about traversing the collection twice
users.view.map(_.getStatus()).foreach(println _)
IOW: Why do you want to manage the iteration yourself (and possibly make mistakes), when you can just let someone else do the work for you?
I prefer scalaj-collection to scala.collection.JavaConversions. This makes the conversions explicit:
import scalaj.collection.Implicits._
val arrayList = new java.util.ArrayList[Int]
arrayList.add(2)
arrayList.add(3)
arrayList.add(4)
arrayList.asScala.map(_ * 2).foreach(println)
Available here: https://github.com/scalaj/scalaj-collection
I suggest using
scala.collection.JavaConverters._
and simply add .asScala
to every object you wish to iterate
精彩评论