How to get the sum of values of certain keys from a map in a more efficient and optimised way?
For example:
var myMap = "SOSSPSSQSSOR".groupBy(identity).mapValues(_.size).toMap
>>myMap: scala.collection.immutable.Map[Char,Int] = Map(Q -> 1, P -> 1, R -> 1, O -> 2, S -> 7)
myMap.sumExcludingValuesFor("S,O")
def sumExcludingValuesFor(s:String):Int = {
//return the sum of the values for keys except S, O
}
My implementation so far:
var charMap = "SOSSPSSQSSOR".toString.groupBy(identity).mapValues(_.size).toMap
var excludeChar = Set('S','O')
var mapExcludingSO = charMap.filterKeys { excludeChar.contains(_) == false }
println(mapOnlySO.values.toList.sum)
But looking for a better implementation than this.
Any help is highly apprecaited!