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
}
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) }
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With