Is there an elegant / idiomatic way to check in Kotlin whether an element of one list is contained in another list?
Given:
val listA = listOf("A", "B", "C")
I can write expressions such as:
listA.intersect(setOf("E", "C")).isNotEmpty()
or:
listA.any { it in listOf("E","C") }
That's OK, but I wonder if there is even a more fluent way to express that (as this code is simplified, the real code is more complex).
My fallback is to use a custom extension function, e.g.:
fun <T> List<T>.containsAny(vararg other : T) =
this.intersect(other.toSet()).isNotEmpty()
I just wonder if there is a better way.
I agree with Louis that setA.any { it in setB }
seems pretty readable, and relies solely on the standard library functions. Alternatively, you could use a method reference to make it a bit more explicit:
setA.any(setB::contains)
Straying a bit further, you could just define your own extension function:
infix fun <T: Any> Set<T>.intersects(other: Set<T>) = any(other::contains)
Then you can just write:
if (setA intersects setB)
EDIT: Given your updated question, I'd note that this extension function can scale to any collection type, or with your varargs approach:
infix fun <T: Any> Collection<T>.intersects(other: Collection<T>) = any(other::contains)
fun <T: Any> Collection<T>.intersects(vararg others: T) = any(other::contains)
So you can still do something like:
if (myList intersects setOf("1", "2", "3"))
or
if (myList.intersects("1", "2", "3"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With