在 Scala 中将 Map 展平为 varargs 字符串列表
Java 事件日志记录(分析)库有一个方法,该方法采用事件名称,然后是可变参数字符串列表,如下所示:
Analytics.event("my event name", "key1", "value1", "key2", "value2" ...)
我已将事件参数收集到像这样的 Map 中
Map("key1" -> "value1", "key2" -> "value2" ...)
,现在必须有一种方法来展平 Map 列出键和值交替的位置,然后将其提供给事件方法。我有几个猜测,比如将 Map
转换为列出 Tuple
的 List
,但调用 .flatten 会显示“
No implicit view available from (java.lang.String, java.lang.String) => scala.collection.TraversableOnce[B]
我是什么”这里不见了?
A Java event logging (analytics) library has a method that takes an event name and then varargs list of Strings like this:
Analytics.event("my event name", "key1", "value1", "key2", "value2" ...)
I've collected my event parameters in to a Map like
Map("key1" -> "value1", "key2" -> "value2" ...)
Now there must be a way to flatten the Map
to list where keys and values alternate and then feed it to the event method. I've had several guesses, like transforming the Map
to list a List
of Tuple
s, but calling .flatten on that says
No implicit view available from (java.lang.String, java.lang.String) => scala.collection.TraversableOnce[B]
What am I missing here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用
: _*
运算符:不确定这是否也适用于 Java 可变参数(请告诉我们!)
You can use the
: _*
operator:Not sure whether this works with Java varargs as well (let us know!)
您可以使用 flatMap 将每个键/值对映射到包含两个元素的列表,然后连接这些列表。
一旦你有了这个,你就可以将列表传递给事件方法:
You can use flatMap to map every key/value pair to a list with two elements and then concatenate these lists.
Once you have that, you can just pass the list to the event method: