我有一个Map [String,String],我想按照特定的顺序打印它,具体取决于键。例如,我想打印id,name,address的值。所以我想将我的键与“id”,“name”,“address”匹配,然后在每个键上打印值。我有以下代码,但它不起作用:
articlesmap.keys match{
case ("id") => println(articlesmap.get("id"))
case ("name") => println(articlesmap.get("name"))
case ("address") => println(articlesmap.get("address"))
}
答案 0 :(得分:8)
您可以使用for
:
for {
k <- Seq("id", "name", "address") // the keys in the order you want to print them.
v <- articlesmap.get(k)
} println (k+ " is " + v)
如果您只想打印值,collect
会很好:
Seq("id", "name", "address") collect articlesmap foreach println
collect
优于map
id,您无法确定某个密钥实际位于地图中。
答案 1 :(得分:3)
这是我所知道的最简单的解决方案:
scala> val keys = Seq("id", "name", "address")
keys: Seq[java.lang.String] = List(id, name, address)
scala> val articlesmap = Map("id" -> 1, "name" -> "john", "address" -> "some address")
articlesmap: scala.collection.immutable.Map[java.lang.String,Any] = Map(id -> 1, name -> john, address -> some address)
scala> keys map articlesmap foreach println
1
john
some address
scala> val keys = Seq("name", "id", "address")
keys: Seq[java.lang.String] = List(name, id, address)
scala> keys map articlesmap foreach println
john
1
some address
答案 2 :(得分:2)
变量articlesmap.keys的类型为Iterable[String]
,但您的案例匹配在类型String
上匹配。试试这个:
def mapTest(map: Map[String, String]) {
map.keys.foreach {
case ("id") => println(map.get("id"))
case ("name") => println(map.get("name"))
case ("address") => println(map.get("address"))
}
}
val mapper = Map("id" -> "123", "name" -> "Bob", "address" -> "123 Fake Street")
mapTest(mapper)
// => Some(123)
// Some(Bob)
// Some(123 Fake Street)
答案 3 :(得分:2)
您可以创建OrderedMap
,也可以对keys
进行排序并处理该类型的结果。