Kotlin Sets

Sets are a data structure that do not allow for duplicate entries. A common use case for sets is when we need to filter out duplicate elements from a list or an array. Like lists, Kotlin has both mutable sets and read-only sets. In addition, there is also a sorted set flavor that inserts elements in a specified order. The sorted set is read only.

Operations

Creation

We use setOf(), mutableSetOf(), sortedSetOf() to create sets. They take any number of parameters.

val belchers = setOf("Bob", "Linda", "Tina", "Gene", "Louise")
val mutableBelchers = mutableSetOf("Bob", "Linda", "Tina", "Gene", "Louise")

val smiths = sortedSetOf("Rick", "Jerry", "Beth", "Summer", "Morty")

Accessing Items

Sets do not overload the index operator. We can access an item with either the first() or last() method, find, or looping through the entire list.

val bob = belchers.first()
val linda = belchers.last()
val gene = belchers.find { it -> it == "Gene" }
words.forEach( {it -> println(it) } )

Testing Membership

We can use the in function to test if the list has an item.

println("Tina" in belchers) //prints true
println("Rick" in belchers) //prints false

Adding or Removing (Mutable Only)

We can use add or remove on mutableSet to change the elements in the set.

mutableBelchers.remove("Tina")
mutableBelchers.add("Tina")

mutableBelchers.add("Bob") //no effect because Bob is already in the set

Putting it Together

This is an example program that finds the unique words in an except from Dr. Suess’s Green Eggs and Ham.

fun main(args : Array<String>){
    val paragraph = """
        I am Sam.
        Sam I am.

        That Sam-I-am!
        That Sam-I-am!
        I do not like
        That Sam-I-am!

        Do you like
        Green eggs and ham?

        I do not like them,
        Sam-I-Am
        I do not like
        Green eggs and ham.
        """
    //Remove punctuation and new line characters
    val cleanParagraph =
            paragraph.replace(".", "")
                     .replace(",", "")
                     .replace("?", "")
                     .replace("\n", "")
    
    //Split the string by space character and convert it into a set
    val words = cleanParagraph.split(" ").toSet()
    
    //Split the string by space character and convert it to a sortedSet
    val sortedWords = cleanParagraph.split(" ").toSortedSet()


    println(words)
    println(sortedWords)
}

Output

[, I, am, Sam, That, Sam-I-am!, do, not, like, Do, you, Green, eggs, and, ham, them, Sam-I-Am]
[, Do, Green, I, Sam, Sam-I-Am, Sam-I-am!, That, am, and, do, eggs, ham, like, not, them, you]
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s