Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: An elegant way to check if a List contains a value of another Collection / List?

Tags:

kotlin

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.

like image 635
Lior Bar-On Avatar asked Oct 23 '18 18:10

Lior Bar-On


1 Answers

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"))
like image 190
Kevin Coppock Avatar answered Oct 25 '22 12:10

Kevin Coppock