Scala updating/creating value in a hashmap
Posted
by
user1672739
on Stack Overflow
See other posts from Stack Overflow
or by user1672739
Published on 2012-10-12T21:10:06Z
Indexed on
2012/10/12
21:37 UTC
Read the original article
Hit count: 135
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?
© Stack Overflow or respective owner