Count occurrences of each element in a List[List[T]] in Scala

后端 未结 3 917
猫巷女王i
猫巷女王i 2020-12-11 03:07

Suppose you have

val docs = List(List(\"one\", \"two\"), List(\"two\", \"three\"))

where e.g. List(\"one\", \"two\") represents a document

3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-11 03:34

    docs.flatten.foldLeft(new Map.WithDefault(Map[String,Int](),Function.const(0))){
      (m,x) => m + (x -> (1 + m(x)))}
    

    What a train wreck!

    [Edit]

    Ah, that's better!

    docs.flatten.foldLeft(Map[String,Int]() withDefaultValue 0){
      (m,x) => m + (x -> (1 + m(x)))}
    

提交回复
热议问题