Scala groupBy for a list

假如想象 提交于 2021-02-07 05:29:18

问题


I'd like to create a map on which the key is the string and the value is the number of how many times the string appears on the list. I tried the groupBy method, but have been unsuccessful with that.


回答1:


Required Answer

scala> val l = List("abc","abc","cbe","cab")
l: List[String] = List(abc, abc, cbe, cab)

scala> l.groupBy(identity).mapValues(_.size) 
res91: scala.collection.immutable.Map[String,Int] = Map(cab -> 1, abc -> 2, cbe -> 1)



回答2:


Suppose you have a list as

scala> val list = List("abc", "abc", "bc", "b", "abc")
list: List[String] = List(abc, abc, bc, b, abc)

You can write a function

scala> def generateMap(list: List[String], map:Map[String, Int]) : Map[String, Int] = list match {
     |       case x :: y => if(map.keySet.contains(x)) generateMap(y, map ++ Map(x -> (map(x)+1))) else generateMap(y, map ++ Map(x -> 1))
     |       case Nil => map
     |     }
generateMap: (list: List[String], map: Map[String,Int])Map[String,Int]

Then call the function as

scala> generateMap(list, Map.empty)
res1: Map[String,Int] = Map(abc -> 3, bc -> 1, b -> 1)


来源:https://stackoverflow.com/questions/47327360/scala-groupby-for-a-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!