如何从 csv 字符串获取地图
我对 Scala 相当陌生,但我现在正在做练习。
我有一个像这样的字符串
"A>Augsburg;B>Berlin"
. What I want at the end is a mapval mymap = Map("A"->"Augsburg", "B"->"Berlin")
我所做的是:
val st = locations.split(";").map(dynamicListExtract _)
with the functionprivate def dynamicListExtract(input: String) = {
if (input contains ">") {
val split = input split ">"
Some(split(0), split(1)) // return key , value
} else {
None
}
}
Now I have anArray[Option[(String, String)
How do I elegantly convert this into a Map[String, String]有人可以帮忙吗? 谢谢
I'm fairly new to Scala, but I'm doing my exercises now.
I have a string like
"A>Augsburg;B>Berlin"
. What I want at the end is a map
val mymap = Map("A"->"Augsburg", "B"->"Berlin")
What I did is:
val st = locations.split(";").map(dynamicListExtract _)
with the function
private def dynamicListExtract(input: String) = {
if (input contains ">") {
val split = input split ">"
Some(split(0), split(1)) // return key , value
} else {
None
}
}
Now I have an
Array[Option[(String, String)
How do I elegantly convert this into a Map[String, String]
Can anybody help?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
只需将
map
调用更改为flatMap
:作为比较:
Just change your
map
call toflatMap
:For comparison:
在 2.8 中,您可以执行以下操作:
collect
类似于map
,但也会过滤部分函数中未定义的值。toMap
将从Traversable
创建一个Map
,只要它是Traversable[(K, V)]
。In 2.8, you can do this:
collect
is likemap
but also filters values that aren't defined in the partial function.toMap
will create aMap
from aTraversable
as long as it's aTraversable[(K, V)]
.Randall 的 for-compression 形式的解决方案也值得一看,它可能更清晰,或者至少让您更好地了解 flatMap 正在做什么。
It's also worth seeing Randall's solution in for-comprehension form, which might be clearer, or at least give you a better idea of what flatMap is doing.
一个简单的解决方案(不处理错误情况):
但 Ben Lings 的更好。
A simple solution (not handling error cases):
but Ben Lings' is better.