36

How does scala.collection.JavaConversions supercede the answers given in Stack Overflow question Iterating over Java collections in Scala (it doesn't work because the "jcl" package is gone) and in Iterating over Map with Scala (it doesn't work for me in a complicated test which I'll try to boil down and post here later).

The latter is actually a Scala Map question, but I think I need to know both answers in order to iterate over a java.util.Map.

Community
  • 1
  • 1
Alex R
  • 11,364
  • 15
  • 100
  • 180

1 Answers1

81

In 2.8, you import scala.collection.JavaConversions._ and use as a Scala map. Here's an example (in 2.8.0.RC1):

scala> val jmap:java.util.Map[String,String] = new java.util.HashMap[String,String]  
jmap: java.util.Map[String,String] = {}

scala> jmap.put("Hi","there")
res0: String = null

scala> jmap.put("So","long")
res1: String = null

scala> jmap.put("Never","mind")
res2: String = null

scala> import scala.collection.JavaConversions._
import scala.collection.JavaConversions._

scala> jmap.foreach(kv => println(kv._1 + " -> " + kv._2))
Hi -> there
Never -> mind
So -> long

scala> jmap.keys.map(_.toUpperCase).foreach(println)
HI
NEVER
SO

If you specifically want a Scala iterator, use jmap.iterator (after the conversions import).

Rex Kerr
  • 166,841
  • 26
  • 322
  • 407
  • Wow, this is a great, painless solution! – rasen58 Jun 14 '17 at 21:35
  • There should be a way without converting to scala map, right ? It will better if we are iterating over java map in a loop, it will avoid unnecessary object creation. Getting " found : (String, String) => Unit required: java.util.function.BiConsumer[_ >: String, _ >: String]" error. – Zxcv Mnb Jun 20 '17 at 15:41
  • 1
    @ZxcvMnb - These days you should use `JavaConverters` and explicitly change them; with Java 8's addition of a `foreach` method, you can't use implicit conversion any more for `foreach`. – Rex Kerr Jun 26 '17 at 23:04