Skip to content

Collections: Removing duplicates

Devrath edited this page Feb 29, 2024 · 1 revision

Removing duplicates from list of strings

code

val input = arrayOf("USA", "Australia", "USA", "Russia", "Russia", "England")

fun main(args: Array<String>) {

    // Maintain original order of items
    println("//--> Maintain original order of items")
    println("<-Distinct-> ${input.distinct()}")
    println("<-ToSet-> ${input.toSet()}")
    println("<-ToMutableSet-> ${input.toMutableSet()}")
    println()
    println("//--> Do Not Maintain original order of items")
    println("<-ToHashSet-> ${input.toHashSet()}")

}

Output

//--> Maintain original order of items
<-Distinct-> [USA, Australia, Russia, England]
<-ToSet-> [USA, Australia, Russia, England]
<-ToMutableSet-> [USA, Australia, Russia, England]

//--> Do Not Maintain original order of items
<-ToHashSet-> [USA, England, Australia, Russia]
Clone this wiki locally