Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the new way to iterate over a Java Map in Scala 2.8.0?

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.

like image 714
Alex R Avatar asked Apr 25 '10 16:04

Alex R


People also ask

How many ways can you iterate a map in Java?

There are generally five ways of iterating over a Map in Java.

Which expression is one way to iterate over a collection in Scala?

A simple for loop that iterates over a collection is translated to a foreach method call on the collection. A for loop with a guard (see Recipe 3.3) is translated to a sequence of a withFilter method call on the collection followed by a foreach call.


1 Answers

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).

like image 100
Rex Kerr Avatar answered Sep 21 '22 13:09

Rex Kerr