Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get min by value only in Scala Map

Tags:

scala

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.

like image 658
dave Avatar asked Jan 05 '12 22:01

dave


People also ask

How do you find the minimum value of a Map?

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.

What is the Map in scala?

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) .


1 Answers

Use minBy:

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

This gives "b" as expected.

like image 107
Travis Brown Avatar answered Sep 21 '22 20:09

Travis Brown