Remove duplicate elements from a list in Kotlin
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.
|
1 2 3 4 5 6 7 8 |
fun main() { // list with duplicate items val list: List<String> = listOf("One", "Two", "One") val distinct = list.toSet().toList(); println(distinct) // [One, Two] } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 |
import java.util.* import kotlin.collections.ArrayList fun main() { // list with duplicate items val list: List<String> = listOf("One", "Two", "One") val distinct: List<String> = LinkedHashSet(list).toMutableList() println(distinct) // [One, Two] } |
2. Using distinct() function
To preserve the original order, you can also use the distinct() function, as shown below:
|
1 2 3 4 5 6 7 8 |
fun main() { // list with duplicate items val list: List<String> = listOf("One", "Two", "One") val distinct = list.distinct().toList() println(distinct) // [One, Two] } |
That’s all about removing duplicate elements from a list in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)