val (key, value) = entry // do stuff with key ...">

"Destruction" Map.Entry in closing Scala

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 destroy Map.Entry? I tried the following, but it does not compile:

 m.foreach { (key, value) => // do stuff with key and value } 
+6
closures scala destructuring
source share
2 answers

If you are ready to do this for understanding, I like:

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

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

  m.foreach{ case (key, value) => println(key, value) } 
+20
source share

This is the answer to the question: how to convert a Java iterator (in this case, through 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()) } 

is displayed

 (yellow,"banana") 
+1
source share

All Articles