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.
To get the min and max values in a Map:Use the values() method to get an iterator object of the Map's values. Using spread syntax, pass the iterator to the Math. min() and Math. max() methods.
A Map is an Iterable consisting of pairs of keys and values (also named mappings or associations). Scala's Predef object offers an implicit conversion that lets you write key -> value as an alternate syntax for the pair (key, value) .
Use minBy
:
Map("a" -> 3.0, "b" -> 1.0, "c" -> 2.0).minBy(_._2)._1
This gives "b"
as expected.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With