How to get min by value only in Scala Map

前端 未结 2 1770
走了就别回头了
走了就别回头了 2021-02-05 13:12

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

相关标签:
2条回答
  • 2021-02-05 13:30

    Use minBy:

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

    This gives "b" as expected.

    0 讨论(0)
  • 2021-02-05 13:40

    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("")
    
    0 讨论(0)
提交回复
热议问题