scala-按数据类型字符串匹配并获取其频率

时间:2019-04-24 20:26:23

标签: scala pattern-matching

我从hive表架构中获取以下数据类型详细信息,并且需要获取其频率

val a = List("decimal(10,2)","string","string","decimal(6,0)",
              "timestamp","decimal(8)", "timestamp" )

val freq = a.map{
  x => x match {
    case  x.contains("decimal") => "decimal" // getting error here
    case "string" => "string"
    case "timestamp" => "date"
  }
}.groupBy(identity).mapValues(_.length)

println(freq)

我说错了,无法解析符号。代码有什么问题?。

我需要输出为

Map(date -> 2, decimal -> 3, string -> 2)

如果有更好的方法来获得上述输出,也欢迎

2 个答案:

答案 0 :(得分:4)

您可以在第一个模式匹配中使用后卫来实现您想要的目的。

val freq = a.map{
  x => x match {
    case  x if  x.contains("decimal") => "decimal" // getting error here
    case "string" => "string"
    case "timestamp" => "date"
  }
}.groupBy(identity).mapValues(_.length)

答案 1 :(得分:4)

您还可以在foldList

val freq = a.foldLeft(Map[String,Int]().withDefaultValue(0)){
  case (m,s) if s.startsWith("decimal") => m + ("decimal" -> (m("decimal")+1))
  case (m,"timestamp") => m + ("date" -> (m("date")+1))
  case (m,str)         => m + (str    -> (m(str)+1))
}