'Scala: how to check if map has values greater than x?

I was wondering what's the most efficient way to check if a map has a value equal or greater than a certain threshold:

for example, if I get the following map:

val x = Map(2 -> 2, 3 -> 1, 4 -> 1, 7 -> 1)

at the moment I wrote:

x.values.max > 2

Is there a more efficient way? How to check if the Map contains a specific value instead?



Solution 1:[1]

You can use scala.collection.Iterator.exists to check whether there exists at least one item of a collection which satisfies a given predicate. To simplify iterating over the Map, you can use scala.collection.Map.valuesIterator:

x.valuesIterator.exists(_ > 2) //=> false
x.valuesIterator.exists(_ > 1) //=> true

Scastie link

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jörg W Mittag