首页 > 解决方案 > 如何在不设置的情况下将映射键转换为字符串?

问题描述

我有val states = Map("AL" -> "Alabama", "AK" -> "Alaska")

我想将键转换statesSeq(String),但我得到Seq(Set(String))了。

我试过了

Seq(states.keys.toString)
res3: Seq[String] = List(Set(AL, AK))

标签: scala

解决方案


您不想在地图中有重复的键。这就是为什么keys返回Set[K]。见keys下面的定义

  /** Collects all keys of this map in a set.
   * @return  a set containing all keys of this map.
   */
  def keySet: Set[K] = new DefaultKeySet

  def keys: Iterable[K] = keySet

.keys实际上 return Iterable[K],您可以.toList/ toSeqonSet更改数据结构。

scala> val states = Map("AL" -> "Alabama", "AK" -> "Alaska")
states: scala.collection.immutable.Map[String,String] = Map(AL -> Alabama, AK -> Alaska)

scala> val stateNames = states.keys.toList
stateNames: List[String] = List(AL, AK)

或者

scala> val stateNames = states.keys.toSeq
stateNames: Seq[String] = Vector(AL, AK)

推荐阅读