1

我有一个 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"))
 }
4

4 回答 4

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

collectmapid 你不能确定一个键实际上在地图中。

于 2013-02-08T05:42:25.267 回答
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
于 2013-02-08T06:14:27.260 回答
2

变量 articlemap.keys 是 type Iterable[String],但您的案例匹配匹配 type 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)
于 2013-02-08T05:41:15.670 回答
2

您可以创建一个OrderedMap或者您可以对排序keys结果进行排序并处理该排序的结果。

于 2013-02-08T05:47:12.203 回答