7
val m: java.util.Map[String, Int] = ...
m.foreach { entry =>
  val (key, value) = entry
  // do stuff with key and value
}

Is there a better way to destructure the Map.Entry? I tried the following, but it does not compile:

m.foreach { (key, value) =>
  // do stuff with key and value
}
Ralph
  • 31,584
  • 38
  • 145
  • 282
  • 3
    You're not destructuring a `Map.Entry`. You implicitly converted the `java.util.Map` to a scala Map, and when you iterate through that, you're actually looking at a `Tuple2`'s. – Ken Bloom Feb 07 '11 at 20:59

2 Answers2

24

If you are willing to do a for comprehension, I like:

for((key, value) <- m) println(key, value)

but assuming you want to do m.foreach, I like

 m.foreach{ case (key, value) => println(key, value) }
agilefall
  • 3,876
  • 3
  • 31
  • 27
  • The `foreach` example you gave worked well, even for a java.util.Map (with `scala.collection.JavaConversions._` in scope). – Ralph Feb 07 '11 at 18:27
1

This answers a related question: how to convert a Java iterator (in this case, over java.util.Map.Entry) to a Scala iterator.

import scala.collection.JavaConverters._
import com.fasterxml.jackson.core.JsonFactory
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.node.{JsonNodeFactory, MissingNode, ObjectNode}

val jf = new JsonFactory(true)
val o = new ObjectNode(jf)
o.put("yellow","banana")

for (v <- o.fields.asScala) { println(v.getKey(),v.getValue()) }

this prints out

(yellow,"banana")
Paul Pham
  • 111
  • 4