Unable to iterate Java list in Scala

I am using the Twitter4J Java library in a Scala project.

I am calling a method

twitter.getFriendsStatuses()

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

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

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

Any ideas?

+5
source share
5 answers

I think it users.iteratorproduces a new iterator every time it is evaluated. Try the following:

val it = users.iterator
while(it.hasNext() ) {
   println(it.next().getStatus())
}
+24
source

If you are using Scala 2.8, you can use JavaConversion to automatically convert a Java collection to a Scala collection.

Ref.

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)
+17
source

users.foreach(user => println(user.getStatus()))

users.map(_.getStatus()).foreach(println _)

,

users.view.map(_.getStatus()).foreach(println _)

IOW: (, , ), - ?

+8

I prefer the 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

+3
source

I suggest using

scala.collection.JavaConverters._

and just add .asScalato each object you want to repeat.

+1
source

All Articles