I have a List[<DataType>]
as input. I want to check if the list contains all the same values(not datatype).
Is there inbuilt method or intuitive way in Scala to do this instead of iterating over list and checking.
Check if all elements are same using list.count() returns the occurrence count of given element in the list. Let's call the count() function of list with firts element of list as argument. If its occurrence count is equal to the length of list, then it means all elements in list are Same i.e.
distinct() Let's look at one particular solution making use of the distinct() method. If the count of this stream is smaller or equal to 1, then all the elements are equal and we return true.
There are 2 ways to understand check if the list contains elements of another list. First, use all() functions to check if a Python list contains all the elements of another list. And second, use any() function to check if the list contains any elements of another one.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With