11.23. Finding the Largest Key or Value in a Map
Problem
You want to find the largest value of a key or value in a map.
Solution
Use the max method on the map,
or use the map’s keysIterator or
valuesIterator with other approaches,
depending on your needs.
For example, given this map:
valgrades=Map("Al"->80,"Kim"->95,"Teri"->85,"Julia"->90)
the key is type String, so
which key is “largest” depends on your definition. You can find the
“largest” key using the natural String sort order by calling the max method on the map:
scala> grades.max
res0: (String, Int) = (Teri,85)Because the “T” in “Teri” is farthest down the alphabet in the names, it is returned.
You can also call keysIterator
to get an iterator over the map keys, and call its max method:
scala> grades.keysIterator.max
res1: String = TeriYou can find the same maximum by getting the keysIterator and using reduceLeft:
scala> grades.keysIterator.reduceLeft((x,y) => if (x > y) x else y)
res2: String = TeriThis approach is flexible, because if your definition of “largest” is the longest string, you can compare string lengths instead:
scala> grades.keysIterator.reduceLeft((x,y) => if (x.length > y.length) x else y)
res3: String = JuliaBecause the values in the map are of type Int in this example, you can use this simple
approach to get the largest value:
scala> grades.valuesIterator.max
res4: Int = 95You can also use the reduceLeft
approach, if you prefer:
scala> grades.valuesIterator.reduceLeft(_ max _)
res5: Int = 95You can also ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access