Praveen L
Praveen L

Reputation: 987

Getting all key value pairs having the maximum value from a Scala map

I have seen a similar post here here which is giving a single key-value pair which has maximum value in the entire Map.

But I would like to get List of pairs which has maximum value(maximum value is same for many pairs).

Ex : Map(1 -> 7, 2 -> 1, 4 -> 7, 3 -> 2)

Expected Output : List(1 -> 7, 4 -> 7)

This (Map(1 -> 7, 2 -> 1, 4 -> 7, 3 -> 2).maxBy(x => x._2)) will give only first occurrence 1 -> 7

Upvotes: 1

Views: 996

Answers (2)

Peter Fitch
Peter Fitch

Reputation: 253

val maxValue = map.values.max
map.filter(_._2 == maxValue).toList

Upvotes: 1

vindev
vindev

Reputation: 2280

Using map.filter(_._2 == map.values.max) will do the trick.

Upvotes: 1

Related Questions