scala - 如何在不设置的情况下将映射键转换为字符串?
问题描述
我有val states = Map("AL" -> "Alabama", "AK" -> "Alaska")
我想将键转换states
为Seq(String)
,但我得到Seq(Set(String))
了。
我试过了
Seq(states.keys.toString)
res3: Seq[String] = List(Set(AL, AK))
解决方案
您不想在地图中有重复的键。这就是为什么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
/ toSeq
onSet
更改数据结构。
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)
推荐阅读
- python - 通过 google colab 将文件保存到 google 驱动器时出错
- javascript - 突出显示悬停行的特定表格单元格
- spring - Spring Redis - @RedisHash 动态设置 timeToLive
- r - 估计随着时间推移主题流行度对 STM 的影响
- android - 用整数更改进度条最大值
- javascript - JSP在动态生成的表行中获取输入标签的值
- google-apps-script - 触发器应该每 5 分钟激活一次,但它不会发生
- c++ - 用于分析多个数据结构的 massif-visualizer
- react-native - 如何正确进行注册
- python - 使用自定义损失函数创建 Keras 模型的函数只能工作一次