【问题标题】:Scala: for-comprehension to turn String into Map[Char, Int] [duplicate]Scala:理解将 String 转换为 Map[Char,Int] [重复]
【发布时间】:2016-07-31 00:28:14
【问题描述】:

在 Scala 中使用 for-comprehension 循环遍历字符串并生成字符映射和表示该字符在字符串中出现次数的整数的好方法是什么?

def mapString(s: String): Map[Char, Int] = {
     for(c<-s) ...
}

【问题讨论】:

    标签: scala dictionary functional-programming for-comprehension


    【解决方案1】:
    def mapString(s: String): Map[Char, Int] = {
        s.groupBy(c => c).map{case(c,str) => c-> str.size}.toMap
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-21
      • 1970-01-01
      • 1970-01-01
      • 2016-08-24
      • 2019-01-01
      相关资源
      最近更新 更多