This article explores different ways to remove duplicate elements from a list in Kotlin without destroying the original ordering of the list elements.

1. Using Set

The idea is to convert the given list to a set collection. This will result in all distinct elements from the list since a set filter out the duplicates.

Download Code

 
As of Kotlin 1.3, toSet() function implementation uses LinkedHashset. Therefore, the original ordering of the elements in the list is not destroyed. However, to ensure the original order regardless of toSet() implementation, you can use the LinkedHashset constructor.

Download Code

2. Using distinct() function

To preserve the original order, you can also use the distinct() function, as shown below:

Download Code

That’s all about removing duplicate elements from a list in Kotlin.