This article explores different ways to determine if all elements of a List are the same in Kotlin.

1. Using Set

The most common solution to validate if all elements of a list are identical or not is converting the list into a set and checking if the set’s size is 1 or not. It works since a set doesn’t allow duplicate values in it. For a list of custom objects, don’t forget to override equals() and hashCode() method.

Download Code

2. Find distinct count

The above set-based solution is very efficient but takes additional space. Alternatively, we can get the count of the distinct elements in the list. If all elements in the list are the same, then the count would be exactly 1. This is demonstrated below using the distinct() function with count() function.

Download Code

3. Using all() function

The all() function returns true if all elements match with the specified predicate. We can use it as follows to determine if all list elements are identical. Note that the predicate compares each element of the list with the first, and an additional check is placed to handle an empty list.

Download Code

4. Using Collections.frequency() function

The idea here is to get the frequency of any element in the list. If the count is equal to the size of the list, we can say that all elements in the list are the same. The following solution uses the Collections.frequency() function to get the count of an element in the list.

Download Code

 
Here’s an equivalent version without using java.util.Collections class:

Download Code

That’s all about determining if all elements of a List are the same in Kotlin.