Kotlin collections intersect

Kotlin provides a lot of useful methods, for which we’d normally have to use Apache Commons or Guava. The Kotlin intersect method is such a method.

We can use the Kotlin intersect method to determine which elements are in both collections, and return a new collection containing those elements.

val one = listOf("Carrots", "Tomatoes", "Cucumber")
val other = listOf("Lettuce", "Tomatoes", "Olives")

val intersect = one.intersect(other)

assert(intersect == listOf("Tomatoes"))

Leave a Reply

Your email address will not be published. Required fields are marked *