Compare two lists in Kotlin for equality
This article explores different ways to compare two lists in Kotlin for equality. Two lists are considered equal if they contain the same number of same elements in the same order.
There are several ways to determine whether two lists are equal to each other. All of these involve making element-by-element comparisons on elements of the lists.
1. Using zip() with all() function
The idea is to use the zip() function to get a list of pairs built from the elements of both lists with the same index. Then you can use the all() function to check if every element of both lists with the same index are equal.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
fun<T> isEqual(first: List<T>, second: List<T>): Boolean { if (first.size != second.size) { return false } return first.zip(second).all { (x, y) -> x == y } } fun main() { val first = listOf(1, 2, 3, 4, 5) val second = listOf(1, 2, 3, 4, 5) val isEqual = isEqual(first, second) println(isEqual) // true } |
2. Using forEachIndexed() function
Another solution is to iterate through one list and check the value present at the corresponding position in the other list. If both values do not match at any index, we can say that the lists are not equal. This can be easily done using the forEachIndexed() function.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
fun<T> isEqual(first: List<T>, second: List<T>): Boolean { if (first.size != second.size) { return false } first.forEachIndexed { index, value -> if (second[index] != value) { return false} } return true } fun main() { val first = listOf(1, 2, 3, 4, 5) val second = listOf(1, 2, 3, 4, 5) val isEqual = isEqual(first, second) println(isEqual) // true } |
3. Using contentEquals() function
Another solution is to convert both lists into an array and use the native contentEquals() function to determine whether both lists are structurally equal.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
inline fun<reified T> isEqual(first: List<T>, second: List<T>): Boolean { if (first.size != second.size) { return false } return first.toTypedArray() contentEquals second.toTypedArray() } fun main() { val first = listOf(1, 2, 3, 4, 5) val second = listOf(1, 2, 3, 4, 5) val isEqual = isEqual(first, second) println(isEqual) // true } |
That’s all about comparing two lists in Kotlin for equality.
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 :)