How to check if list contains all the same values?
One (inefficient but elegant) way is
List(1, 2, 2, 1, 1).distinct.length == 1 // returns false
List(1, 1, 1, 1, 1).distinct.length == 1 // returns true
List().distinct.length == 1 // empty list returns false
Note that they must be of the same type
List(4, 4.0, "4").distinct.length == 1 // returns false
This will terminate on the first non-equals element. The element type has to support a comparator like ==
or !=
.
lst.forall(_ == lst.head) // true if empty or all the same
lst.exists(_ != lst.head) // false if empty or all the same
I just had to do this for an unrelated problem, so to improve on the above ever so slightly: lst.tail.forall(_ == lst.head)
. This avoids checking that the head of the list equals itself, which you already know is true.