Reputation: 4811
I have a map of type Map[String, String] with keys like:
"dealership_id_1"
"dealership_id_3"
"dealership_id_7"
"dealership_id_39"
How can I get the largest value of the ID from the keys? i.e. in this case it is 39
Would it be difficult to extract the id values into a list?
List(1, 3, 7, 39)
My map has maybe 100 keys so it should be a performance issue I would imagine.
Upvotes: 0
Views: 281
Reputation: 1986
I do agree with the @Alvaro Carrasco solution but map.keys.map()
actually creates new collection. I would rather stick to Iterator
which does not do that:
def maxKeySuffix[T](map: Map[String, T]): Int =
map.keys.iterator.map(_.stripPrefix("dealership_id_").toInt).max
Upvotes: 0
Reputation: 40500
Use the regex:
val id = """_(\d+)""".r
val ids = map.keys.collect { case id(x) => x }
Upvotes: 0
Reputation: 6172
map.keys.map(_.stripPrefix("dealership_id_").toInt).max // 39
100 entries is not very many
Upvotes: 4