To check if two arrays have the same elements regardless of order in Kotlin, you can convert both arrays to sets and compare the sets.
In this example,
arr1
and arr2
with integer values.toSet
method. This step removes any duplicate elements and disregards the order of elements.==
. If the sets are equal, it means the original arrays have the same elements regardless of order.fun main(args: Array<String>) {
val arr1 = arrayOf(1, 2, 3, 4, 5)
val arr2 = arrayOf(5, 4, 3, 2, 1)
val areSame = arr1.toSet() == arr2.toSet()
println("Do arr1 and arr2 have the same elements: $areSame")
}
Do arr1 and arr2 have the same elements: true
In this example,
arr1
and arr2
with string values.toSet
method. This step removes any duplicate elements and disregards the order of elements.==
. If the sets are equal, it means the original arrays have the same elements regardless of order.fun main(args: Array<String>) {
val arr1 = arrayOf("apple", "banana", "cherry")
val arr2 = arrayOf("cherry", "banana", "apple")
val areSame = arr1.toSet() == arr2.toSet()
println("Do arr1 and arr2 have the same elements: $areSame")
}
Do arr1 and arr2 have the same elements: true
In this example,
arr1
and arr2
with integer values.toSet
method. This step removes any duplicate elements and disregards the order of elements.==
. If the sets are not equal, it means the original arrays do not have the same elements regardless of order.fun main(args: Array<String>) {
val arr1 = arrayOf(1, 2, 3, 4, 5)
val arr2 = arrayOf(1, 2, 3, 6, 7)
val areSame = arr1.toSet() == arr2.toSet()
println("Do arr1 and arr2 have the same elements: $areSame")
}
Do arr1 and arr2 have the same elements: false
In this example,
arr1
and arr2
with string values.toSet
method. This step removes any duplicate elements and disregards the order of elements.==
. If the sets are not equal, it means the original arrays do not have the same elements regardless of order.fun main(args: Array<String>) {
val arr1 = arrayOf("apple", "banana", "cherry")
val arr2 = arrayOf("apple", "banana", "date")
val areSame = arr1.toSet() == arr2.toSet()
println("Do arr1 and arr2 have the same elements: $areSame")
}
Do arr1 and arr2 have the same elements: false
In this tutorial, we learned How to check if Two Arrays have Same Elements (Regardless of Order) in Kotlin language with well detailed examples.