Here is a code snippet that sums up the values in a map in Scala:
It may look cryptic at first but once you get the Scala feel, you will appreciate its conciseness and elegance. Here below is the explanation:
m stands for a Map, foldLeft is a method that takes an initial value (0 here since sum is 0 at the beginning) and feeds it to its next iteration on this map entry. Note that the first _ stands for the result of previous iteration result. And _+_._2 means:
take previous result and add it to the next map entry's value, which _._2 stands for. In Scala, Map values can be accessed as Tuples. _1 is the key and _2 is the value. Here is a working example:
scala> val m = Map("one"->1,"two"->2,"three"->3)
m: scala.collection.immutable.Map[java.lang.String,Int] = Map(one -> 1, two -> 2, three -> 3)
res0: Int = 6
Note: You can change + to * and use 1 for the initial value to get the product of values.
- P12: Decode run-length encoding
- P11: Modified run-length encoding that includes on...
- Installing Eclipse, Scala and Groovy in Windows 7
- P10: Run-length encoding of a list.
- P09: Pack consecutive duplicates of list elements...
- P08: Eliminate consecutive duplicates of list elem...
- P07: Flatten a list
- P06: Is a list palindrome
- P03 - P05: Find nth element, length, reverse a lis...
- How to simply sum values in a Map in Scala
- Best Note Taking Tools
- P02: Find the last but one element of a list.
- Over all these years of Software development, I ca...
- ▼ October (13)