Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the maximum key value pair in a Scala map by value

I am trying to pull the maximum value form a map along with its key. For example:

val map = Map('a' -> 100, 'b' -> 23, ... 'z' -> 56)

Where 100 is the largest value, how would I go about pulling ('a',100)? I essentially want to use Map.max but search by value rather than key.

like image 657
pmaurais Avatar asked Sep 26 '16 22:09

pmaurais


People also ask

How do you find the max value in Scala?

Scala Int max() method with exampleThe max() method is utilized to return the maximum value of the two specified int numbers. Return Type: It returns true the maximum value of the two specified int numbers.

How do you access Map elements in Scala?

Scala Map get() method with exampleThe get() method is utilized to give the value associated with the keys of the map. The values are returned here as an Option i.e, either in form of Some or None. Return Type: It returns the keys corresponding to the values given in the method as argument.

How does Map store key-value pairs?

Java HashMap. Java HashMap class implements the Map interface which allows us to store key and value pair, where keys should be unique. If you try to insert the duplicate key, it will replace the element of the corresponding key. It is easy to perform operations using the key index like updation, deletion, etc.


2 Answers

You can use maxBy with a function from the key-value pair to just the value:

val map = Map('a' -> 100, 'b' -> 23, 'z' -> 56)

map.maxBy(_._2)  // (a,100)

This is a short form for

map.maxBy { case (key, value) => value }
like image 160
0__ Avatar answered Oct 06 '22 01:10

0__


A slight modification in case the max value you are looking for is present more than once in the map:

// Find the entries with the max value in the map
val maxValue = map.maxBy(item => item._2)

// Filter the map and retain the entries with the max value
map.filter(item => item._2 == maxValue._2)
like image 36
Victor Avatar answered Oct 06 '22 01:10

Victor