Generating a frequency map for a string in Scala

后端 未结 4 1141
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-29 04:46

Let\'s say I have a string, \"hello\", and I want to generate a character frequency map:

Map[Char,Int] = Map(h -> 1, e -> 1, o -> 1, l -> 2)
         


        
4条回答
  •  萌比男神i
    2020-12-29 05:13

    Your example on ruby can be almost directly translated to Scala using foldLeft and immutable Map.

    Here is one of possible solutions:

    str.foldLeft(Map[Char, Int]() withDefaultValue 0){(h, c) => h.updated(c, h(c)+1)}
    

    Actually, if you are ok with local mutability, you can make something like this:

    def charFrequencies(str: String): collection.Map[Char, Int] = {
      val hash = collection.mutable.HashMap.empty[Char, Int] withDefaultValue 0
      str foreach { hash(_) += 1 }
      hash
    }
    

    Expression hash(_) += 1 will be desugared to c => hash(c) = hash(c) + 1 and then to c => hash.update(c, hash.apply(c) + 1)

    This solution should be more efficient than functional ones, because it don't create intermediate collections. Also because method returns immutable collection.Map[Char, Int], result will be treated as immutable (as long as no one will perform unsafe downcasting on it).

提交回复
热议问题