Android Programming – Part 8 Kotlin Fundamentals Ⅷ: Collection Filters

Filtering everything!

The filter function is one of Kotlin’s prominent ways to reduce repetitiveness in codes and shapes the entire coding scheme tight and readable.

Kotlin’s filtering functions are quite unique and very clean when compared to other legacy languages’ syntax, such as Java or C/C++. This is some way of eliminating the repetitive if-statement, isn’t it? Here’s a description from Kotlin’s official page.

Filtering is one of the most popular tasks in collection processing. In Kotlin, filtering conditions are defined by predicates – lambda functions that take a collection element and return a boolean value: true means that the given element matches the predicate, false means the opposite.

The standard library contains a group of extension functions that let you filter collections in a single call. These functions leave the original collection unchanged, so they are available for both mutable and read-only collections. To operate the filtering result, you should assign it to a variable or chain the functions after filtering.

kotlinlang.org

And here are some of the codes I coded on my Linux environment.

filer {} by length

CollectionFilter2.kt

fun listOfMyMutableSet(myList: MutableList<String>) {
    val found = myList.filter {
        it.length > 4
    }
    println(found)
}

fun main() {
    val mylist = mutableListOf("James", "Sam", "Foxx")
    listOfMyMutableSet(mylist)
}
$java -jar CollectionFilter2.jar
[James]

filer {} by ‘==’ match-comparison

CollectionFilter3.kt

fun listOfMyMutableSet(myList: MutableList<String>) {
    val found = myList.filter {
        it == "James"
    }
    println(found)
}

fun main() {
    val mylist = mutableListOf("James", "Sam", "Foxx")
    listOfMyMutableSet(mylist)
}
$java -jar CollectionFilter3.jar
[James]

filer {} with endsWith() function

CollectionFilter4.kt

fun listOfMyMutableSet(myList: MutableList<String>) {
    val found = myList.filter {
        it.endsWith("x")
    }
    println(found)
}

fun main() {
    val mylist = mutableListOf("James", "Sam", "Foxx")
    listOfMyMutableSet(mylist)
}
johnito@skynewubuntuserver:testdir$ java -jar CollectionFilter4.jar
[Foxx]

filer {} with startsWith() function

CollectionFilter5.kt

fun listOfMyMutableSet(myList: MutableList<String>) {
    val found = myList.filter {
        it.startsWith("J", ignoreCase = true)
    }
    println(found)
}

fun main() {
    val mylist = mutableListOf("James", "Sam", "Foxx")
    listOfMyMutableSet(mylist)
}
johnito@skynewubuntuserver:testdir$ java -jar CollectionFilter5.jar
[James]

via:

kotlinlang.org

Leave a Reply