How to find the largest key or value in a Scala Map

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 11.24, “How to Find the Largest Key or Value in a Scala Map


You want to find the largest value of a key or value in a Scala Map.


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 compare the numbers yourself, which is representative of what you may need to do with more complex types:

scala> grades.valuesIterator.reduceLeft((x,y) => if (x > y) x else y)
res6: Int = 95

To find minimum keys and values, just reverse the algorithms in these examples.

See Also

  • Recipe 11.19, “Getting the Keys or Values from a Map”

The Scala Cookbook

This tutorial is sponsored by the Scala Cookbook, which I wrote for O’Reilly:

You can find the Scala Cookbook at these locations:

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.