scala - 字符串中唯一字符的数量

标签 scala

我需要编写一个返回 List 的函数的 (Char, Int)对给定输入 String .

我的解决方案产生了正确的结果,但我想知道是否有更好的方法:

def countChars(s: String): List[(Char, Int)] = {
    s.groupBy(c => c.toLower).flatMap(e => List((e._1, e._2.length))).toList
  }                                              

这会在工作表中产生如下结果:
countChars("Green Grass")
// res0: List[(Char, Int)] = List(('e', 2), ('s', 2), ('n', 1), ('a', 1), (' ', 1), ('g', 2), ('r', 2))

最佳答案

制作一个单例列表只是为了扁平化它是多余的。

"Green Grass".groupBy(c => c.toLower).map(e => (e._1, e._2.length)).toList

关于scala - 字符串中唯一字符的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23847338/

相关文章:

json - 使用 Circe 将包含 HList 的案例类解析为 JSON 字符串

mysql - 通过 Play 使用 ScalaAnorm 访问多个数据库

Scala:哪个隐式参数优先?定义方法时声明的那个?或者该方法在哪里被调用?

scala - 使用 Spray-json 解析简单数组

scala - Scala 中变量的返回类型

scala - 错误 : expected class or object definition

scala - 配置 Scalaxb SBT 插件生成的源代码位置

scala - 为 NetBeans 设置 Scala - 错误

Scala 排序集 : I cannot get how ordering works