4

Can anybody help how to get the the maximum value in a map along with its key. For example map below:

Map(s -> 3, h -> 2, M -> 1, q-> 4)

I should get the key value (q -> 4) as the 4 is the highest.

I tried the max method,keys and values iterator. But none of the return both key and value.

Mohan
  • 221
  • 1
  • 21

3 Answers3

3

You can use maxBy as

val map_values = Map("s" -> 3, "h" -> 2, "M" -> 1, "q"-> 4)
println(map_values.maxBy(_._2))
//(q,4)
Ramesh Maharjan
  • 41,071
  • 6
  • 69
  • 97
2

You can get what you want as follows:

 map.filter{case (k,v) => v == map.values.max}

With map.values.max you get the max value, and inserting it into the filter statement you obtain the whole key-value pair

SCouto
  • 7,808
  • 5
  • 32
  • 49
  • 1
    This answer is more complete, because unlike the other answers, this yields all keys that have the max value, not just a single one of them, when multiple keys have the same max value. Of course, for a very large map or critical code sections, you might want something finer for performance sake. – matanster May 18 '18 at 19:10
1

How does this look like for you?

map.maxBy { case (key, value) => value }
joesan
  • 13,963
  • 27
  • 95
  • 232