Determine if all elements of a Kotlin List are same
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.
|
1 2 3 4 5 6 |
fun main() { val input = (1.. 10).map { 0 } val isEqual = mutableSetOf(input).size == 1 println(isEqual) // true } |
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.
|
1 2 3 4 5 6 |
fun main() { val input = (1.. 10).map { 0 } val isEqual = input.distinct().count() == 1 println(isEqual) // true } |
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.
|
1 2 3 4 5 6 |
fun main() { val input = (1.. 10).map { 0 } val isEqual = input.isEmpty() || input.all { input[0] == it } println(isEqual) // true } |
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.
|
1 2 3 4 5 6 |
fun main() { val s = (1.. 10).map {""} val isEqual = s.isEmpty() || java.util.Collections.frequency(s, s[0]) == s.size println(isEqual) // true } |
Here’s an equivalent version without using java.util.Collections class:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
fun main() { val input = listOf(2, 2, 2, 2) var isEqual = true for (e in input) { if (e != input[0]) { isEqual = false } } println(isEqual) // true } |
That’s all about determining if all elements of a List are the same in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)