Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Destructuring" a Map.Entry in a Scala closure

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
}
like image 405
Ralph Avatar asked Feb 07 '11 17:02

Ralph


2 Answers

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) }
like image 116
agilefall Avatar answered Nov 08 '22 03:11

agilefall


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")
like image 1
Paul Pham Avatar answered Nov 08 '22 04:11

Paul Pham