Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if list contains all the same values?

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.

like image 604
Deepak Punjabi Avatar asked Jan 05 '17 05:01

Deepak Punjabi


People also ask

How do you check if all values in list are the same?

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.

How do you check if all values in list are same in Java?

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.

How do you check if a list contains all elements of another list?

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.


1 Answers

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
like image 98
jwvh Avatar answered Oct 23 '22 09:10

jwvh