This article explores different ways to compare two lists in Kotlin, where the order of elements is ignored.

For instance, the lists [4, 1, 5] and [1, 4, 5] are considered equal, and the lists [4, 1, 5] and [5, 4, 3] are not considered equal. The size of both lists should be equal. Therefore, the lists [4, 1, 5, 4] and [1, 4, 5, 1] are not considered equal.

 
The plausible solution is to sort both lists and then compare them using the == operator. A typical implementation of this approach would look like below. The code gracefully handles the null input and also check if the size of both lists is the same or not before sorting. The solution does not destroy the original order of both lists.

Download Code

Output:

Lists are equal

 
The time complexity of the above solution is O(n.log(n)), where n is the size of the larger list. If the elements count doesn’t matter, you can avoid sorting by converting both lists to a set before comparing them using the == operator.

Download Code

Output:

Lists are equal

That’s all about comparing two lists in Kotlin, where the order of elements is ignored.