Filter in Kotlin

The filter function returns a list containing all elements matching the given condition. We will create a list of numbers and filter the list based on even or odd.

For example, get only even number from the list and set. Even number s number when you divide the number by 2 the modulo must be 0.

The filter method is good for an immutable collection as it doesn't modify the original collection but returns a new one. Below are immutable list and set


fun main(args: Array<String>) {
    var sampleList = listOf(1, 2, 3, 4, 5, 6)
    var even = sampleList.filter { it % 2 == 0 }
    println(" the even numbers are "+even)
    var sampleSet = setOf(1, 2, 3, 4, 5, 6)
    var odd = sampleSet.filter { it % 2 ==1 }
    println(" the odd numbers are "+odd)
}

Let's write one more example with data class.


data class Person(var name:String, var age:Int)
fun main(args: Array<String>) {
    var sampleList = listOf(Person("karthiq", 27), Person("chercherTech", 1))
    // lets filter object which has age is less than 10
    println(sampleList.filter { it.age <10 })
}

We cannot apply filter() method to Kotlin Map as it has keys and values, so we have to apply filterKeys(), filterValues() functions to manipulate the Kotlin Map.


fun main(args: Array<String>) {
    var sampleMap = mapOf(1 to "one", 2 to "two", 3 to "three", 4 to "four")
    var even = sampleMap.filterKeys { it % 2 == 0 }
    println(" the even numbered keys are :"+even)
    var odd = sampleMap.filterValues { it == "two" }
    println(" the value which match with 'two' :"+odd)
}

The filter function has a lot of different options that can improve your code style:

  • filterNot(Predicate: Item -> Boolean) : It's the same as the filter but it returns items which do not meet the predicate condition.
  • filterIndexed(Predicate: (Int, Item) -> Boolean) : Here an index of collection items was added.
  • filterIsInstance<>() : It checks the type of collection elements and returns the new collection.
  • filterNotNull() : It guarantees that you’ll receive a collection with non-null elements.

And of course all functions with the "to"? suffix are also public (e.g filterTo, filterNotTo, etc). Using these functions you can define the collection object that will hold the filtering result.

Comparison Operator Overloading

map() function in Kotlin

map() function returns a list of the results after applying the given function to each item of a given list/set


fun main(args: Array<String>) {
    var sampleList = listOf(1, 2, 3, 4, 5, 6)
    var mul = sampleList.map { it * 3 }
    println("The result of mutiplication "+mul)
    var sampleSet = setOf(1, 2, 3, 4, 5, 6)
    var sub = sampleSet.map { it - it } // expecting everything result to be zer0
    println("The result of subtraction "+ sub)
}

Lets write example with data class object


data class Person(var name:String, var age:Int)
fun main(args: Array<String>) {
    var sampleList = listOf(Person("karthiq", 27), Person("chercherTech", 1))
    // get only names
    println(sampleList.map { it.name})
}

We cannot apply map() function to Kotlin Map as it has keys and values, so we have to apply mapKeys(), mapValues() functions to manipulate the Kotlin Map.


fun main(args: Array<String>) {
    var sampleMap = mapOf(1 to "one", 2 to "two", 3 to "three", 4 to "four")
    var even = sampleMap.mapKeys { it.key * 5 }
    println("keys are multiplied by 5 :"+even)
    var odd = sampleMap.mapValues { it.value + "_kotlin" }
    println("values are :"+odd)
}

lambda in Kotlin

all()

all() function returns `true` if all elements match the given predicate/condition, if any element is not meeting the condition then all() function returns false.


fun main(args: Array<String>) {
    var sampleList = listOf(2, 4, 6)
    var conditionForList = sampleList.all { it%2 == 0 }
    println("all elements meets condition "+conditionForList)
    var sampleSet = setOf(2, 4, 5)
    var conditionForSet = sampleSet.all { it % 2 == 0 }
    // 5 will not meets cndtion
    println("all elements meets condition  "+conditionForSet)
}

any()

all() function returns `true` if any element matches the given predicate/condition in the list/set, if not element is not meeting the condition then any() function returns false.


fun main(args: Array<String>) {
    var sampleList = listOf(7, 3, 6)
    var conditionForList = sampleList.any { it%2 == 0 }
    println("any element meets condition "+conditionForList)
    var sampleSet = setOf(1, 3, 5)
    var conditionForSet = sampleSet.any { it % 2 == 0 }
    // 5 will not meets condition
    println("any elements meets condition  "+conditionForSet)
}

count()

count() function returns the number of elements matching the given condition/predicate.


fun main(args: Array<String>) {
    var sampleList = listOf(7, 4, 6)
    var conditionForList = sampleList.count { it%2 == 0 }
    println("no.Of elements meets condition "+conditionForList)
    var sampleSet = setOf(10, 3, 5)
    var conditionForSet = sampleSet.count { it % 2 == 0 }
    // 5 will not meets condition
    println("no.Of elements meets condition  "+conditionForSet)
}

find{} & findLast{}

find{} returns the first element matching the given condition/predicate, or `null` if no such element was found.

findLast{} returns the last element matching the given condition/predicate, or `null` if no such element was found.

Let me ask you something, if a function can return null and not null value then what is the return of that function ??

True, it is Nullable Type, I hope, you remember that to call a function from nullable we have to make a check that the object is not null.

Because of this reason, I have added a null check using the if condition.


data class Person(var name:String, var age:Int)
fun main(args: Array<String>) {
    var sampleList = listOf(Person("karthiq", 27), Person("chercherTech", 1))
    // get only names
    var personObject = sampleList.find { it.name == "chercherTech"}
    if(personObject != null){
        println(personObject.name)
        println(personObject.age)
    }
}

Object Oriented Programming

Count vs Size

Size provide the number of elements present in the collection, size does not depend on any type of condition/predicate in collection.

Count is also an indirect size but count() function has implementation where the kotlin applies a condition/predicate over a collection, Now from the result of this predicate, the kotlin applies a size property on it, to get the count of matches.

The last two lines shows how the count works


fun main(args: Array<String>) {
    var sampleList = listOf(7, 4, 6)
    println("Total elements in list : "+ sampleList.size)
    var conditionForList = sampleList.count { it%2 == 0 }
    println("no.Of elements meets condition "+conditionForList)
    // below is waht happens internally
    var usingSizeCount = sampleList.filter { it%2 == 0 }.size
    println("no.Of elements meets condition "+usingSizeCount)
}

in keyword aka contains()

in keyword is mainly used for looping purpose but we can use the in keyword to check whether a collection contains some value.


fun main(args: Array<String>) {
    var sampleList = listOf(7, 4, 6)
    println(4 in sampleList)
    println(55 in sampleList)
	 println(75 !in sampleList)
    println(sampleList.contains(6))
}

kotlin groupBy

groupBy() is used to group elements of the given collection by the key returned by the given [keySelector] function. Result of groupBy is a map collection.

Complete code for kotlin groubBy example


data class Person(var name:String, var age:Int)
fun main(args: Array<String>) {
    var sampleList = listOf(Person("karthiq", 27), Person("chercherTech", 1),
Person("pk", 27), Person("selenium-webdriver.com", 1))
    // get only names
    var personObjectList = sampleList.groupBy { it.age}
    println(personObjectList)
}

count() with group By

We can fetch the count of groups resulted because of groupBy condition/predicate.

Complete code for kotlin groubBy code


data class Person(var name:String, var age:Int)
fun main(args: Array<String>) {
    var sampleList = listOf(Person("karthiq", 27), Person("chercherTech", 1),
Person("pk", 27), Person("selenium-webdriver.com", 1))
    // get only names
    var personObjectList = sampleList.groupBy { it.age}
    println(personObjectList.count())
}

joinToString() in kotlin

sometmes, ypu might want to combine the value in a list to form a string wiht help of some separator, In these cases the joinToString() combines the values in the list.


fun main(args: Array<String>) {
    var sampleList = listOf(1, 2, 3)
    var joinedString = sampleList.joinToString( " ======= " )
    println(joinedString)
}

Secondary Constructors in kotlin

aaaaaaaaaaaaa
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions

Recent Addition

new tutorial Selenium Online Training : Our next online training course for Selenium with Java starts from 17th December 2018.

You can attend first 3 classes for free, the total course fee is INR 10,000

The course time would be 8.00 PM(IST) for the first three classes

If you are interested to learn, then you can join the course by sending email to chercher.tech@gmail.com

or Register below


 
Join My Facebook Group
Join Group