Skip to content
DeveloperMemos

Removing Duplicates from an Array in Kotlin

Kotlin, Android Development1 min read

When working with arrays in Kotlin, it's common to encounter situations where you need to eliminate duplicate elements. This can be crucial for ensuring data consistency and creating efficient algorithms. In this article, we will explore various techniques for removing duplicates from an array in Kotlin, providing clear examples for each method.

Using distinct()

One of the simplest ways to remove duplicates from an array in Kotlin is by using the distinct() function. This function returns a list containing only distinct elements from the original list. Here's an example:

1fun main() {
2 val numbers = listOf(1, 2, 3, 4, 2, 3, 5, 6, 7, 1)
3 val distinctNumbers = numbers.distinct()
4 println(distinctNumbers) // Output: [1, 2, 3, 4, 5, 6, 7]
5}

In the above example, distinctNumbers contains only the unique elements from the numbers list.

Using toSet()

Another approach involves converting the array to a Set and then back to a List. Since Sets do not allow duplicate elements, this method effectively removes duplicates. Here's how you can achieve this:

1fun main() {
2 val numbers = listOf(1, 2, 3, 4, 2, 3, 5, 6, 7, 1)
3 val uniqueNumbers = numbers.toSet().toList()
4 println(uniqueNumbers) // Output: [1, 2, 3, 4, 5, 6, 7]
5}

In this example, uniqueNumbers contains the distinct elements from numbers.

Using distinctBy()

The distinctBy() function allows for more complex logic by letting you specify a selector function to determine uniqueness. This function takes a lambda that extracts a key from each element, and then returns a list containing only elements with distinct keys. Here's an example:

1data class Person(val id: Int, val name: String)
2
3fun main() {
4 val people = listOf(Person(1, "Alice"), Person(2, "Bob"), Person(1, "Alice"))
5 val distinctPeople = people.distinctBy { it.id }
6 println(distinctPeople) // Output: [Person(id=1, name=Alice), Person(id=2, name=Bob)]
7}

In the above example, distinctPeople contains only those Person objects with distinct id values.