This article explores different ways to compare two lists for equality in Kotlin.

1. Using == operator

A simple solution to check two lists for equality is using the == operator. It returns true if the size of both lists is the same, and all corresponding pairs of elements in both lists are equal.

Download Code

Output:

Both lists are equal

 
This is equivalent to calling the equals() function. Alternatively, you can use the deepEquals() function for comparing two lists in Kotlin. It returns true if the lists are “deeply” equal to each other and false otherwise.

2. Using zip() function

Another plausible way is to use the zip() function that returns the list of pairs built from the elements of both lists with the same index. Since the returned list has the length of the shortest list, you should compare the size of both lists first.

Download Code

Output:

Both lists are equal

3. Comparing List of objects

To compare two lists of objects in Kotlin, the objects are required to have a correct and stable implementation of the equals and hashCode functions. The following program demonstrates its usage:

Download Code

Output:

Both lists are equal

 
Alternatively, you can use a data class that automatically overrides both the equals() and hashCode() functions.

Download Code

Output:

Both lists are equal

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