16

I have a map that has SomeClass -> Double I want to get the SomeClass associated with the smallest value. How do I go about doing this? Ties do not matter and can be broken arbitrarily if that is an issue.

Philippe
  • 9,582
  • 4
  • 39
  • 59
dave
  • 12,406
  • 10
  • 42
  • 59

2 Answers2

39

Use minBy:

Map("a" -> 3.0, "b" -> 1.0, "c" -> 2.0).minBy(_._2)._1

This gives "b" as expected.

Travis Brown
  • 138,631
  • 12
  • 375
  • 680
1

Starting Scala 2.13, you might prefer minByOption in order to also safely handle empty Maps:

Map("a" -> 3.0, "b" -> 1.0, "c" -> 2.0).minByOption(_._2).map(_._1)
// Some("b")
Map[String, Double]().minByOption(_._2).map(_._1)
// None

And you can always decide to fallback on a default value when the Map is empty:

Map[String, Double]().minByOption(_._2).map(_._1).getOrElse("")
Xavier Guihot
  • 54,987
  • 21
  • 291
  • 190