Scala groupBy 用于列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47327360/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 09:30:11  来源:igfitidea点击:

Scala groupBy for a list

scalalist

提问by T.Simmari

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 groupBymethod, but have been unsuccessful with that.

我想创建一个映射,其键是字符串,值是字符串在列表中出现的次数。我尝试了该groupBy方法,但没有成功。

回答by Mahesh Chand

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)

回答by Ramesh Maharjan

Suppose you have a listas

假设你有一个清单作为

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 functionas

然后将函数调用为

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