Kotlin Collections Class

Kotlin and JDK have a number of extension methods that make working with collection classes easier.

Extension Methods

sort()

The sort() method sorts elements by their natual order. It also has an overloaded version that takes a comparator that allows for custom sorting.

val belchers = mutableListOf(
            "Bob",
            "Linda",
            "Tina",
            "Gene",
            "Louise")
belchers.sort()

binarySearch(T) : Int

The binarySearch function applies the binary search algorithm to the collection and returns the index of the element or -1 if not found. The list has to be sorted first.

belchers.sort()
belchers.binarySearch("Gene") //returns 1

Conversion Methods

Kotlin provides methods that allow for each switching between collection types.

val setBelchers = belchers.toSet()
val listBelchers = belchers.toList()

Populating a List

Collections can be populated with a generator function. Here is an example for a list.

val teddies = List(10){ "Teddy" }
println(teddies) //prints: [Teddy, Teddy, Teddy, Teddy, Teddy, Teddy, Teddy, Teddy, Teddy, Teddy]

max()

The max() function returns the maximum element in the collection. There is an overloaded version that takes a comparator.

val max = belchers.max()

min()

The min() function returns teh minimum element in the collection. There is an overloaded version that takes a comparator.

val min = belchers.min()

replaceAll

The replaceAll takes a lambda expression and replaces all elements according to the lambda function. Here is an example that replaces all occurences of “Tina” with “Mort”.

belchers.replaceAll { it -> if(it == "Tina") "Mort" else it }

addAll

The addAll function takes a list and adds all elements in the list to the collection.

belchers.addAll(teddies)

removeAll

The removeAll takes a collection and removes all matches from the current collection.

belchers.removeAll(teddies)

reverse()

The revesere() method reverses the order of the elements in the collection.

belchers.reverse()

Note

The functions demonstrated above are on MutableList. They may or may not be present on other collection types such as List, Set, or MutableSet. See the Kotlin documentation for more details.

Collections

Oddly, not all of the methods found in the Collections class have been implemented as extension functions. Here are two common functions found in the Collections class.

shuffle

Randomizes the elements in the list.

Collections.shuffle(belchers)

swap

Swaps the elements at the specified indexes.

Collections.swap(belchers, 0, 3)

Putting it Together

Below is an example program that demonstrates the mentioned functions.

import java.util.*

fun main(args : Array<String>){
    val belchers = mutableListOf(
            "Bob",
            "Linda",
            "Tina",
            "Gene",
            "Louise")

    println("Soring the belchers")
    belchers.sort()
    println("After sorting => " + belchers + "\n")

    println("Using Binary Search")
    println("Gene Found at Index => " + belchers.binarySearch("Gene"))

    //Make a read-only copy of belchers
    val belchersCopy = belchers.toList()
    println("Read only copy => " + belchersCopy + "\n")

    //Filling a list
    val teddies = List(10) { "Teddy"}
    println("Printing teddies => " + teddies + "\n")

    println("Finding the max belcher => " + belchers.max() + "\n")

    println("Find the min belcher => " + belchers.min() + "\n")

    println("Replacing Tina")
    belchers.replaceAll { it -> if(it == "Tina") "Mort" else it }
    println("After replacing Tina => " + belchers + "\n")

    println("Adding teddies...")
    belchers.addAll(teddies)
    println("After adding teddies => " + belchers + "\n")

    println("Removing all teddies...")
    belchers.removeAll(teddies)
    println("After removing teddies => " + belchers + "\n")

    println("Reversing belchers")
    belchers.reverse()
    println("After reversing => " + belchers + "\n")

    //Methods in the Collections class that haven't been made
    //into extension functions
    println("Shuffling belchers...")
    Collections.shuffle(belchers)
    println("After shuffling => " + belchers + "\n")


    println("Swapping 0 and 3")
    Collections.swap(belchers, 0, 3)
    println("After swap => " + belchers)
}

Output

Soring the belchers
After sorting => [Bob, Gene, Linda, Louise, Tina]

Using Binary Search
Gene Found at Index => 1
Read only copy => [Bob, Gene, Linda, Louise, Tina]

Printing teddies => [Teddy, Teddy, Teddy, Teddy, Teddy, Teddy, Teddy, Teddy, Teddy, Teddy]

Finding the max belcher => Tina

Find the min belcher => Bob

Replacing Tina
After replacing Tina => [Bob, Gene, Linda, Louise, Mort]

Adding teddies...
After adding teddies => [Bob, Gene, Linda, Louise, Mort, Teddy, Teddy, Teddy, Teddy, Teddy, Teddy, Teddy, Teddy, Teddy, Teddy]

Removing all teddies...
After removing teddies => [Bob, Gene, Linda, Louise, Mort]

Reversing belchers
After reversing => [Mort, Louise, Linda, Gene, Bob]

Shuffling belchers...
After shuffling => [Linda, Gene, Louise, Mort, Bob]

Swapping 0 and 3
After swap => [Mort, Gene, Louise, Linda, Bob]
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