Kotlin Tip #40: Explore the distinct and distinctBy for removing duplicates from collections — 100 Kotlin Tips in 100 Days

Raphael De Lio
Kotlin with Raphael De Lio
2 min readMar 23, 2024

--

Twitter | LinkedIn | YouTube | Instagram
Tip #39: Use sortBy and sortedBy for Collection Sorting

The distinct function is a straightforward tool for removing duplicate elements from a collection. It returns a list containing only unique elements from the original collection. The beauty of distinct lies in its simplicity and its ability to work with any type of collection. Whether you're dealing with a list of integers, strings, or custom objects, distinct can sift through the collection, ensuring that each element is unique.

Here’s a simple example to demonstrate its usage:

In this example, distinct examines the list of numbers and removes the duplicates, resulting in a list of unique numbers.

While distinct is incredibly useful, there are scenarios where you might want to remove duplicates based on a specific property or criterion. This is where distinctBy comes into play. The distinctBy function allows you to define a selector function that determines the uniqueness of each element.

Consider a collection of User objects, where each User has a name and an age. If you wanted to remove users with duplicate names, regardless of their age, distinctBy makes this task straightforward:

In the above code, distinctBy is used to filter users by their name property, effectively ignoring the age property when determining uniqueness.

Using distinct and distinctBy not only simplifies your code but also enhances its readability and maintainability. However, when working with large collections or complex objects, keep performance considerations in mind. Both distinct and distinctBy require traversing the entire collection, which can be computationally expensive for large datasets.

I hope you have enjoyed this tip of our series! Don’t forget to subscribe and stay tuned for more Kotlin tips!

Stay curious!

Tip #41: Coming soon!

Contribute

Writing takes time and effort. I love writing and sharing knowledge, but I also have bills to pay. If you like my work, please, consider donating through Buy Me a Coffee: https://www.buymeacoffee.com/RaphaelDeLio

Or by sending me BitCoin: 1HjG7pmghg3Z8RATH4aiUWr156BGafJ6Zw

Follow Me on Social Media

Stay connected and dive deeper into the world of Kotlin with me! Follow my journey across all major social platforms for exclusive content, tips, and discussions.

Twitter | LinkedIn | YouTube | Instagram

--

--