Compare two Lists in Kotlin with order ignored
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
fun isEqualIgnoreOrder(x: List<Int>?, y: List<Int>?): Boolean { if (x == y) { return true } if (x == null || y == null || x.size != y.size) { return false } return x.sorted().toList() == y.sorted().toList() } fun main() { val x = listOf(4, 1, 5) val y = listOf(1, 4, 5) val isEqual = isEqualIgnoreOrder(x, y) if (isEqual) { println("Lists are equal") } else { println("Lists are not equal") } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
fun isEqualIgnoreCount(x: List<Int>?, y: List<Int>?): Boolean { if (x == y) { return true } if (x == null || y == null) { return false } return x.toSet() == y.toSet() } fun main() { val x = listOf(4, 1, 5, 4) val y = listOf(1, 4, 5, 1, 5) val isEqual = isEqualIgnoreCount(x, y) if (isEqual) { println("Lists are equal") } else { println("Lists are not equal") } } |
Output:
Lists are equal
That’s all about comparing two lists in Kotlin, where the order of elements is ignored.
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 :)