Determine if all values are same in a Kotlin array
This article explores different ways to determine if all values in an array are the same in Kotlin.
1. Using a Set
A simple solution is to convert the given array into a Set and get its size. If the size of the Set is 1, we can say that all values in the array are the same.
|
1 2 3 4 5 6 |
fun main() { val array: IntArray = intArrayOf(1, 1, 1, 1, 1) val allEqual = array.toSet().size == 1 println(allEqual) // true } |
2. Using distinct() function
The idea here is to get the distinct element count of the array. If the count is 1, all elements in the array must be equal. This would translate to a simple code below:
|
1 2 3 4 5 6 |
fun main() { val array: IntArray = intArrayOf(1, 1, 1, 1, 1) val allEqual = array.distinct().count() == 1 println(allEqual) // true } |
3. Using all() function
Alternatively, we can check if all values are equal to the first element of the array. The cleanest way to do this is using the all() function, as shown below:
|
1 2 3 4 5 6 |
fun main() { val array: IntArray = intArrayOf(1, 1, 1, 1, 1) val allEqual = array.size == 1 || array.all { it == array[0] } println(allEqual) // true } |
Here’s an equivalent version without using the all() function:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
fun isAllEqual(array: IntArray?): Boolean { if (array == null || array.isEmpty()) { return false } for (i in 1 until array.size) { if (array[0] != array[i]) { return false } } return true } fun main() { val array: IntArray = intArrayOf(1, 1, 1, 1, 1) println(isAllEqual(array)) // true } |
That’s all about determining if all values in an array 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 :)