3

I don't understand this with Scala hasmaps: How do I create a value or update one if it does not exist?

I am tryng to count the number of characters in a list of Strings.

I've tried this code but it doesn't work :

 def times(chars: List[Char]): List[(Char, Int)] = {
     val map = new HashMap[Char, Int]()
     chars.foreach(
        (c : Char) => {
           map.update(c, map.get(c) + 1)
        })
 } 

I understand the returning type isn't correct. But is my foreach loop wrong? Is there a prettier way to write it?

1
  • 1
    I would suggest anonymizing code snippets so that they are not directly taken from the Coursera course assignments, especially in light of the recent "academic fraud" alerts. Commented Oct 15, 2012 at 17:32

2 Answers 2

3

I think this will answer your question:

scala> "abaccdba".groupBy(identity).mapValues(_.length)
res3: scala.collection.immutable.Map[Char,Int] = Map(b -> 2, d -> 1, a -> 3, c -> 2)

Oh, and btw HashMap has a method getOrElseUpdate as to your original question

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you very much. I think that updating or creating a map value using the previous value (if there is) can be interesting. How Is it possible?
See the API
Well beleving the API GetOrElseUpdate update only if there is no value. Whereas I'd like to update always. There is an update method but it doesn't use the previous value.
1

If someone wonder how to use GetOrElseUpdate and find this post here is the exemple I found :

val map = Map('a' -> 1, 'b' -> 2)         //> map  :  
scala.collection.immutable.Map[Char,Int] = Map(a -> 1, b -> 2)
val newval = map.getOrElse('b', 0) + 1      //> newval  : Int = 3
val updated = map + ('b' -> (newval))        //> updated  : 
scala.collection.immutable.Map[Char,Int] = Map(a -> 1, b -> 3)

1 Comment

You can also say "Map(...) withDefaultValue 0" instead of using getOrElse.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.