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.

Download Code

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.

Download Code

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.

Download Code

That’s all about comparing two lists in Kotlin for equality.