Skip to content

Instantly share code, notes, and snippets.

@tlux
Last active September 2, 2024 18:13
Show Gist options
  • Save tlux/8f68b71449f0b87b4054ca833c09ca62 to your computer and use it in GitHub Desktop.
Save tlux/8f68b71449f0b87b4054ca833c09ca62 to your computer and use it in GitHub Desktop.
Kotlin extensions to find duplicates in an Iterable
/**
* Gets a set of duplicates in the given iterable.
*/
fun <T> Iterable<T>.duplicates(): Set<T> = duplicatesBy { it }
/**
* Gets a set of duplicates in the given iterable using the specified selector.
*/
fun <T, K> Iterable<T>.duplicatesBy(selector: (T) -> K): Set<K> =
groupingBy(selector).eachCount().filterValues { it > 1 }.keys.toSet()
import io.kotest.core.spec.style.DescribeSpec
import io.kotest.matchers.shouldBe
class DuplicatesSpec : DescribeSpec({
describe("duplicates") {
it("returns empty set when no duplicates found") {
val list = listOf(1, 2, 3, 4, 5)
list.duplicates() shouldBe emptySet()
}
it("gets duplicates") {
val list = listOf(1, 2, 2, 3, 4, 4, 4, 5)
list.duplicates() shouldBe setOf(2, 4)
}
}
describe("duplicatesBy") {
it("returns empty set when no duplicates found") {
val list = listOf("a" to 1, "b" to 2, "c" to 3)
list.duplicatesBy { it.second } shouldBe emptySet()
}
it("gets duplicates for items grouped by a custom selector") {
val list = listOf("a" to 1, "b" to 2, "c" to 2, "d" to 2, "e" to 3, "f" to 3, "g" to 4)
list.duplicatesBy { it.second } shouldBe setOf(2, 3)
}
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment