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:
val
grades
=
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 = Teri
You 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 = Teri
This 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 = Julia
Because 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 = 95
You can also use the reduceLeft
approach, if you prefer:
scala> grades.valuesIterator.reduceLeft(_ max _)
res5: Int = 95
You can also ...
Get Scala Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.