简体   繁体   English

Scala - 将映射键值对转换为字符串

[英]Scala - Convert map key value pair to string

I have to convert Map to string with given 2 delimiters and I wanted to use my own delimiter 我必须使用给定的2个分隔符将Map转换为字符串,并且我想使用自己的分隔符

I have done with the below code 我已完成以下代码

Map("ss"-> "yy", "aa"-> "bb").map(data => s"${data._1}:${data._2}").mkString("|")

The out out is ss:yy|aa:bb 出局是ss:yy | aa:bb

I'm looking for the better way. 我正在寻找更好的方法。

I believe that mkString is the right way of concatenating strings with delimiters. 我相信mkString是用分隔符连接字符串的正确方法。 You can apply it to the tuples as well for uniformity, using productIterator : 您可以使用productIterator将它应用于元组以及均匀性:

Map("ss"-> "yy", "aa"-> "bb")
  .map(_.productIterator.mkString(":"))
  .mkString("|")

Note, however, that productIterator loses type information. 但请注意, productIterator会丢失类型信息。 In the case of strings that won't cause much harm, but can matter in other situations. 在字符串不会造成太大伤害的情况下,但在其他情况下可能很重要。

Map("ss" -> "yy", "aa" -> "bb").map{case (k, v) => k + ":" + v}.mkString("|")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM