Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get value with the lowest key value from Map[Int, String]

Tags:

scala

Say I have a map: Map[Int, String]. How would I get the value [String] with the lowest key [Int]. I've been trying to implement this functionally, but just can't figure out how to do this.

like image 808
Dark Avatar asked Apr 08 '26 18:04

Dark


1 Answers

The following code will get you a value with a lowest key (ignoring some corner cases).

def lowestKeyMember[A](m: Map[Int,A]): A = m(m.keys.min)

This will break ties arbitrarily and throw on an empty map. If you need to do this operation frequently and/or on large maps, you should look into SortedMap.

like image 129
ziggystar Avatar answered Apr 11 '26 07:04

ziggystar