Kotlin underrated feature of Distinct and DistinctBy

<p>Recently I got to know about kotlin feature for removing duplicate from a list. Here is more detailed example of using the&nbsp;<code>distinct</code>&nbsp;and&nbsp;<code>distinctBy</code>&nbsp;methods in Kotlin to remove duplicates from a list:</p> <pre> data class Item(val id: Int, val name: String)</pre> <pre> fun main() { val items = listOf( Item(1, &quot;Apple&quot;), Item(2, &quot;Banana&quot;), Item(3, &quot;Apple&quot;), Item(4, &quot;Orange&quot;), Item(5, &quot;Banana&quot;), Item(3, &quot;Apple&quot;) ) // Using distinct to remove exact duplicates val distinctItems = items.distinct() println(&quot;Distinct Items:&quot;) distinctItems.forEach { println(it) } // Using distinctBy to remove duplicates based on a property (e.g., name) val distinctItemsByName = items.distinctBy { it.name } println(&quot;Distinct Items by Name:&quot;) distinctItemsByName.forEach { println(it) } }</pre> <p>In this example, the&nbsp;<code>distinct</code>&nbsp;function removes exact duplicates from the list of items. The output would be:</p> <pre> Distinct Items: Item(id=1, name=Apple) Item(id=2, name=Banana) Item(id=3, name=Apple) Item(id=4, name=Orange) Item(id=5, name=Banana)</pre> <p>The&nbsp;<code>distinctBy</code>&nbsp;function, on the other hand, removes duplicates based on a specific property&mdash;in this case, the&nbsp;<code>name</code>&nbsp;property. The output for&nbsp;<code>distinctItemsByName</code></p> <pre> Distinct Items by Name: Item(id=1, name=Apple) Item(id=2, name=Banana) Item(id=4, name=Orange)</pre> <p>As mentioned earlier, these methods are not specific to Android development, but they can be used in any Kotlin project. If you&rsquo;re using these methods in an Android app, you can adapt the concepts to your app&rsquo;s architecture (e.g., using&nbsp;<code>RecyclerView</code>&nbsp;to display the results).</p> <p><a href="https://medium.com/@hemantchand/kotlin-underrated-feature-of-distinct-and-distinctby-497f41f23bd">Website</a></p>