无法在 Scala 中迭代 Java 列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5299283/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Unable to iterate Java List in Scala
提问by Sri
I'm using the Java Twitter4J library in a Scala project.
我在 Scala 项目中使用 Java Twitter4J 库。
I'm calling the method
我正在调用方法
twitter.getFriendsStatuses()
This method returns a list of twitter4j.User objects containing statuses.
此方法返回包含状态的 twitter4j.User 对象列表。
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?
有任何想法吗?
回答by axtavt
I guess users.iteratorproduces the new iterator each time it's evaluated. Try this:
我想users.iterator每次评估都会产生新的迭代器。试试这个:
val it = users.iterator
while(it.hasNext() ) {
println(it.next().getStatus())
}
回答by Brian Hsu
If you use Scala 2.8, you could use JavaConversion to convert Java collection to Scala collection automatically.
如果您使用 Scala 2.8,您可以使用 JavaConversion 将 Java 集合自动转换为 Scala 集合。
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)
回答by J?rg W Mittag
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?
IOW:当您可以让其他人为您完成工作时,您为什么要自己管理迭代(并且可能会犯错误)?
回答by Kris Nuttycombe
I prefer scalaj-collection to scala.collection.JavaConversions. This makes the conversions explicit:
与 scala.collection.JavaConversions 相比,我更喜欢 scalaj-collection。这使得转换显式:
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
回答by Ohad Navon
I suggest using
我建议使用
scala.collection.JavaConverters._
scala.collection.JavaConverters._
and simply add .asScalato every object you wish to iterate
并简单地添加.asScala到您希望迭代的每个对象

