I am working on a Scala project and I have a Map of type Map[Long, Tuple2[Boolean, List[Int]]].
I need to assign the total number of elements in all lists within the map to a variable.
I currently have a working solution, however, I want a more efficient solution. I am sure I have heard people say that you can use something called flatMap. So essentially, I want to know if there is a solution that doesn't require a loop, where I can say add the length of all lists in the map.
My solution was as follows:
for((k, v) <- myMap) total = total + v._2.length
In terms of efficiency, your execution would always be
O(n)in your map.If you want to use a more declarative approach, you can use
foldLeft:foldLefttakes a seed as it's first parameter list, which we can initialize to0. And then we iterate through each one of the lists, summing them up and returning the intermediate result. When we reach the end of the key value pair, the last accumulated element will be returned as the result.