Krzysztof Słowiński
Krzysztof Słowiński

Reputation: 7227

Checking if a given element in all the tuples contained in the collection is equal

Having a collection of tuples I would like to check if a given element in all the tuples is equal.

For example considering the second element of all tuples in this array should return false:

val a = Array((4,2), (8,1), (9,4), (10,2), (13,1))

While considering the second element of all the tuples in this array should return true:

val b = Array((4,3), (8,3), (9,3), (10,3), (13,3))

Upvotes: 3

Views: 99

Answers (2)

Mario Galic
Mario Galic

Reputation: 48420

Try

a.forall { case (key, value) => value == a.head._2 } // res2: Boolean = false
b.forall { case (key, value) => value == b.head._2 } // res3: Boolean = true

Note in the case of empty array Array.empty[(Int, Int)] this solution returns true.

Inspired by https://stackoverflow.com/a/41478838/5205022

Upvotes: 3

Gal Naor
Gal Naor

Reputation: 2397

If I understood your question correctly, you can do it like this:

val a = Array((4,2), (8,1), (9,4), (10,2), (13,1))
val b = Array((4,3), (8,3), (9,3), (10,3), (13,3))

a.map(_._2).toSet.size == 1 // false
b.map(_._2).toSet.size == 1 // true

You can play with it here

Upvotes: 6

Related Questions