Search code examples
scalacollectionstuplesequality

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))

Solution

  • 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