To check if two lists have the same elements regardless of order in Kotlin, you can sort both lists and then compare them.
In this example,
list1
and list2
with the same set of elements.sorted
function.equals
method to check if the sorted list1
equals the sorted list2
.fun main() {
val list1 = listOf(1, 2, 3)
val list2 = listOf(3, 2, 1)
val result = list1.sorted() == list2.sorted()
println("Do the lists have the same elements? $result")
}
Do the lists have the same elements? true
In this example,
list1
and list2
with different sets of elements.sorted
function.equals
method to check if the sorted list1
equals the sorted list2
.fun main() {
val list1 = listOf(1, 2, 3)
val list2 = listOf(4, 5, 6)
val result = list1.sorted() == list2.sorted()
println("Do the lists have the same elements? $result")
}
Do the lists have the same elements? false
In this tutorial, we learned How to check if Two Lists have Same Elements (Regardless of Order) in Kotlin language with well detailed examples.