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 <code>distinct</code> and <code>distinctBy</code> 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, "Apple"),
Item(2, "Banana"),
Item(3, "Apple"),
Item(4, "Orange"),
Item(5, "Banana"),
Item(3, "Apple")
) // Using distinct to remove exact duplicates
val distinctItems = items.distinct()
println("Distinct Items:")
distinctItems.forEach { println(it) } // Using distinctBy to remove duplicates based on a property (e.g., name)
val distinctItemsByName = items.distinctBy { it.name }
println("Distinct Items by Name:")
distinctItemsByName.forEach { println(it) }
}</pre>
<p>In this example, the <code>distinct</code> 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 <code>distinctBy</code> function, on the other hand, removes duplicates based on a specific property—in this case, the <code>name</code> property. The output for <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’re using these methods in an Android app, you can adapt the concepts to your app’s architecture (e.g., using <code>RecyclerView</code> to display the results).</p>
<p><a href="https://medium.com/@hemantchand/kotlin-underrated-feature-of-distinct-and-distinctby-497f41f23bd">Website</a></p>