Kotlin

distinct, distinctBy, intersect, union

admin by @admin ADMIN
Jun 14, 2026
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
Set-style ops on collections. `distinct` removes duplicates; `distinctBy` lets you key the dedupe by a derived value; `union/intersect/subtract` give you set operations.
Kotlin
Raw
fun main() {
    val xs = listOf(1, 2, 2, 3, 3, 3, 4)

    println(xs.distinct())                              // [1, 2, 3, 4]

    // distinctBy — dedupe by something derived
    val users = listOf("Alice@x.com", "BOB@x.com", "alice@X.com", "Carol@x.com")
    val uniqueByLower = users.distinctBy { it.lowercase() }
    println(uniqueByLower)                              // [Alice@x.com, BOB@x.com, Carol@x.com]

    // Set ops on lists
    val a = listOf(1, 2, 3, 4)
    val b = listOf(3, 4, 5, 6)
    println(a.union(b))                                 // [1, 2, 3, 4, 5, 6]
    println(a.intersect(b))                             // [3, 4]
    println(a.subtract(b))                              // [1, 2]

    // Element-level membership
    println(3 in a)                                     // true
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.